package com.icinfo.cloud.provider.punish.ucase.caseregister.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.*;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.*;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.dto.DisposalBackResultDto;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.dto.TripartiteStatusDto;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.service.ITaskCenterService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.app.enums.AppCaseConvertTemporaryEnum;
import com.icinfo.cloud.provider.punish.app.service.IAppCaseConvertTemporaryRecordService;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalCompleteRecordMapper;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalWaitRecordMapper;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalCompleteRecord;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalWaitRecord;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonPreviewDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.config.dto.RelationWorkflowInfoRequest;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentInfoMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamMain;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamMainService;
import com.icinfo.cloud.provider.punish.config.service.IConfigRegisterCaseFileService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.LineCaseHandleInfoVo;
import com.icinfo.cloud.provider.punish.csource.manage.dto.CaseSourceDetailDto;
import com.icinfo.cloud.provider.punish.csource.manage.dto.FlowCommonDto;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceEnum;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceStatusEnum;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterDetailInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterMainInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceHandlePersonRecord;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterDetailInfo;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterMainInfo;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceFlowRecordService;
import com.icinfo.cloud.provider.punish.dataprocessing.model.DataProcessCaseMainInfoDelRecord;
import com.icinfo.cloud.provider.punish.dataprocessing.service.IDataProcessCaseMainInfoDelRecordService;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.external.cadjjbxx.service.impl.ExternalService;
import com.icinfo.cloud.provider.punish.external.dto.EntBaseInfoDto;
import com.icinfo.cloud.provider.punish.external.vo.EntBaseInfoVo;
import com.icinfo.cloud.provider.punish.fastcase.dto.FastCaseRegisterInfoQueryDto;
import com.icinfo.cloud.provider.punish.fastcase.dto.FastCaseRegisterSaveDto;
import com.icinfo.cloud.provider.punish.fastcase.enums.SimpleFormTypeEnum;
import com.icinfo.cloud.provider.punish.fastcase.service.IFastCaseRegisterService;
import com.icinfo.cloud.provider.punish.fastcase.vo.FastCaseRegisterInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentCatalogChainDetailVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseReasonMainRecordVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.*;
import com.icinfo.cloud.provider.punish.ucase.caseregister.service.ICaseRegisterService;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.*;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentSendinfoConfirmMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.workflow.common.annotation.WorkFlowRollAnnotation;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDetailInfoService;
import com.icinfo.cloud.xzcf.provider.member.line.dto.LineDTO;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.MapUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.Collator;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 立案实现类
 *
 * @author lxj
 * @date 2022/2/24
 **/
@Slf4j
@Service
@EnableAspectJAutoProxy(exposeProxy = true) //
public class CaseRegisterServiceImpl extends MyBatisServiceSupport implements ICaseRegisterService {

    @Resource
    ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CasePartiesPersonInfoMapper casePartiesPersonInfoMapper;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private IConfigBusiParamMainService configBusiParamMainService;
    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Resource
    private IRegisterCommonService commonService;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private ICaseTemporaryRecordService caseTemporaryRecordService;
    @Resource
    private CaseTemporaryRecordMapper caseTemporaryRecordMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ExternalService externalService;

    @Value("${member.url}")
    private String url;
    @Value("${member.api.getZfPeopleList}")
    private String zfPeopleListUrl;
    @Value("${spring.profiles.active}")
    private String env;
    @Value("${isCheckHandleSign}")
    private String isCheckHandleSign;
    @Value("${repeatCaseParamOfYears}")
    private String repeatCaseParamOfYears;
    @Value("${member.api.getOrgListByTopOrg}")
    private String orgListByTopOrgUrl;
    @Value("${member.api.getDeptListByTopOrg}")
    private String deptListByTopOrgUrl;
    @Resource
    private IRegisterCommonService registerCommonService;
    @Autowired
    private IConfigWorkFlowDetailInfoService configWorkFlowDetailInfoService;

    @Resource
    private CaseApprovalWaitRecordMapper caseApprovalWaitRecordMapper;

    @Resource
    private CaseApprovalCompleteRecordMapper caseApprovalCompleteRecordMapper;
    @Resource
    private ICasePartiesLegalInfoService casePartiesLegalInfoService;
    @Resource
    private ICasePartiesPersonInfoService casePartiesPersonInfoService;
    @Resource
    private ICaseRelatedDocumentRecordService caseRelatedDocumentRecordService;

    @Resource
    private CaseRelatedDocumentRecordMapper caseRelatedDocumentRecordMapper;
    @Resource
    private ICaseReasonMainRecordService caseReasonMainRecordService;
    @Resource
    private CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;
    @Resource
    private ICaseSourceFlowRecordService caseSourceFlowRecordService;
    @Resource
    private CaseSourceHandlePersonRecordMapper caseSourceHandlePersonRecordMapper;
    @Resource
    private ITaskCenterService taskCenterService;
    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService;
    @Resource
    private CaseSourceRegisterDetailInfoMapper caseSourceRegisterDetailInfoMapper;
    @Resource
    private CaseDocumentRecordHisMapper caseDocumentRecordHisMapper;
    @Resource
    private IConfigRegisterCaseFileService configRegisterCaseFileService;
    @Resource
    private IDataProcessCaseMainInfoDelRecordService mainInfoDelRecordService;
    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    @Resource
    private IFastCaseRegisterService fastCaseRegisterService;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;

    @Resource
    private IAppCaseConvertTemporaryRecordService appCaseConvertTemporaryRecordService;


    /*
     * 更新或添加案由表
     *  flag  true 添加，false 更新
     */
    private void updateReasonRecord(CaseMainInfoDto caseMainInfoDto, boolean flag) {

        if (!flag) {
            //之前老数据更新为失效
            Example example = new Example(CaseReasonMainRecord.class);
            example.createCriteria().andEqualTo("caseId", caseMainInfoDto.getCaseId());
            List<CaseReasonMainRecord> recordList = caseReasonMainRecordMapper.selectByExample(example);
            if (recordList != null && recordList.size() > 0) {
                for (CaseReasonMainRecord record : recordList) {
                    record.setStatus(Constant.STRING_0);
                    caseReasonMainRecordMapper.updateByPrimaryKey(record);
                }
            }
        }
        CaseReasonMainRecord reasonMainRecord = new CaseReasonMainRecord();
        reasonMainRecord.setCaseId(caseMainInfoDto.getCaseId());
        reasonMainRecord.setCreateTime(LocalDateTime.now());
        reasonMainRecord.setId(BaseUtil.createUid());
        reasonMainRecord.setCaseReasonCode(caseMainInfoDto.getCaseReasonCode());
        reasonMainRecord.setCaseReasonName(caseMainInfoDto.getCaseReason());
        reasonMainRecord.setIllegalBasis(caseMainInfoDto.getIllegalBasis());
        reasonMainRecord.setIllegalDetail(caseMainInfoDto.getIllegalDetail());
        reasonMainRecord.setPunishBasis(caseMainInfoDto.getPunishBasis());
        reasonMainRecord.setPunishDetail(caseMainInfoDto.getPunishDetail());
        reasonMainRecord.setItemVersionCode(caseMainInfoDto.getItemVersionCode());
        reasonMainRecord.setTerritoryCode(caseMainInfoDto.getTerritoryCode());
        reasonMainRecord.setClaimId(caseMainInfoDto.getClaimId());
        reasonMainRecord.setStatus(Constant.STRING_1);

        reasonMainRecord.setCaseReasonNameSimple(BaseUtil.handleCaseReason(caseMainInfoDto.getCaseReason()));
        reasonMainRecord.setIllegalBasisFormat(BaseUtil.removeHtml(caseMainInfoDto.getIllegalBasis()));
        reasonMainRecord.setIllegalDetailFormat(BaseUtil.removeHtml(caseMainInfoDto.getIllegalDetail()));
        reasonMainRecord.setPunishBasisFormat(BaseUtil.removeHtml(caseMainInfoDto.getPunishBasis()));
        reasonMainRecord.setPunishDetailFormat(BaseUtil.removeHtml(caseMainInfoDto.getPunishDetail()));

        String nodeIds = "";
        for (String str : caseMainInfoDto.getCaseReasonIds()) {
            if (StringUtils.isEmpty(nodeIds)) {
                nodeIds = str;
            } else {
                nodeIds = nodeIds + "," + str;
            }
        }
        reasonMainRecord.setCaseReasonNodeid(nodeIds);
        caseReasonMainRecordMapper.insertSelective(reasonMainRecord);
    }

    /**
     * 删除立案数据
     *
     * @param caseId 入参
     * @return boolean
     * @author lxj
     * @date 2022/2/22
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delCase(String caseId, String documentCatalogCode) {
        //删除判断是否具有删除权限-wait
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfo, null)) {
            throw new BusinessException("当前案件状态不允许进行该操作");
        }
        if (caseMainInfo == null) {
            return true;
        }
        if (StringUtils.isNotBlank(caseMainInfo.getCaseNumber())) {
            throw new BusinessException("当前案件已立案不允许进行该操作");
        }

        //判断是否案件阶段
        //简案快办在告知阶段可以删除
        if (StringUtils.isNotEmpty(caseMainInfo.getCaseCurrentStageCode()) && (!"CASE_REGISTER".equals(caseMainInfo.getCaseCurrentStageCode()) && !"PUNISH_INFORM".equals(caseMainInfo.getCaseCurrentStageCode()))) {
            throw new BusinessException("非立案登记不能删除案件");
        }
        //如果是案源转立案,删除立案审批表操作
        if (ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfo.getDataSource())) {
            //作废立案审批表文书
            String kindCode = DocumentKindEnum.DOC_KIND_LASPB.getCode();
            CaseDocumentRecordDto caseDocumentRecordByKindCode = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, kindCode);
            CaseDocumentRecord record = new CaseDocumentRecord();
            record.setId(caseDocumentRecordByKindCode.getId());
            record.setDocumentRecordStatus(DocumentRecordStatusEnum.WITHDRAW.getCode());
            caseDocumentRecordMapper.updateByPrimaryKeySelective(record);
            //todo 先删除,后续优化
            //删除宽表数据
            caseMainDetailInfoMapper.deleteByPrimaryKey(caseId);
            //删除案件删除记录
            mainInfoDelRecordService.delRecord(caseId);
        }


        //获取立案登记表中的content内容
        /*String kindCode = DocumentKindEnum.DOC_KIND_LASPB.getCode();
        List<ConfigBusiParamDocumentInfo> configList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId, null, kindCode);
        if (!ObjectUtils.isEmpty(configList)) {
            documentCatalogCode = configList.get(Constant.INTEGER_0).getDocumentCatalogCode();
        } else {
            throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",kindCode:" + kindCode);
        }
        caseMainDetailInfoMapper.deleteByPrimaryKey(caseId);
        //2.删除当事人表多当事人
        List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfoVoList(caseId);
        for (CasePartiesRecordVo recordVo : casePartiesRecords) {
            if (recordVo.getPartyType().equals(Constant.STRING_1)) {
                casePartiesPersonInfoMapper.deleteByPrimaryKey(recordVo.getPartyId());
            } else if (recordVo.getPartyType().equals(Constant.STRING_2)) {
                casePartiesLegalInfoMapper.deleteByPrimaryKey(recordVo.getPartyId());
            }
            casePartiesRecordMapper.deleteByPrimaryKey(recordVo.getId());
        }
        //3.删除办案人员表--2个
        caseHandlePersonRecordService.deleteCaseHandlePersonRecordByCaseId(caseId);
        //4.添加附件表
        Example appendixRecordExample = new Example(CaseAppendixRecord.class);
        appendixRecordExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode);
        caseAppendixRecordMapper.deleteByExample(appendixRecordExample);
        //7.删除案由表
        Example reasonExample = new Example(CaseReasonMainRecord.class);
        reasonExample.createCriteria().andEqualTo("caseId", caseId);
        caseReasonMainRecordMapper.deleteByExample(reasonExample);*/
        //8.调用文书公共接口删除文书记录
        /*CaseDocumentRecordDelRequest caseDocumentRecordDelRequest = new CaseDocumentRecordDelRequest();
        caseDocumentRecordDelRequest.setCaseId(caseId);
        caseDocumentRecordDelRequest.setDocumentCatalogCode(documentCatalogCode);
        for (int i = 0; i < casePartiesRecords.size(); i++) {
            caseDocumentRecordDelRequest.setPartyId(casePartiesRecords.get(i).getPartyId());
            caseDocumentRecordService.delCaseDocumentRecordInfo(caseDocumentRecordDelRequest);
        }*/
        // 删除待审批表，已审批表
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        CaseApprovalWaitRecord caseApprovalWaitRecord = new CaseApprovalWaitRecord();
        caseApprovalCompleteRecord.setCaseId(caseId);
        caseApprovalWaitRecord.setCaseId(caseId);
        caseApprovalWaitRecordMapper.delete(caseApprovalWaitRecord);
        //caseApprovalCompleteRecordMapper.delete(caseApprovalCompleteRecord);
        //删除补充表
        /*Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        caseMainDetailAuxiliaryInfoMapper.deleteByExample(example);*/
        //删除关联文书
        //caseRelatedDocumentRecordService.deleteCaseRelatedDocumentByCaseId(caseId);
        //备份主表
        CaseMainInfo caseInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        DataProcessCaseMainInfoDelRecord dataProcessCaseMainInfoDelRecord = BeanUtil.toBean(caseInfo, DataProcessCaseMainInfoDelRecord.class);
        dataProcessCaseMainInfoDelRecord.setCaseLinkTag("业务删除");
        mainInfoDelRecordService.saveRecord(dataProcessCaseMainInfoDelRecord);
        //删除主表
        caseMainInfoMapper.deleteByPrimaryKey(caseId);
        return true;
    }

    /**
     * 预览
     *
     * @param registerSaveDto
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2022/05/28
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> getCasePreview(CaseRegisterSaveDto registerSaveDto) {
        Map<String, Object> map = new HashMap<>();
        UserDTO userInfo = UserUtil.getUserInfo();
        if (userInfo == null) {
            map.put("msg", "未登录或登录信息已失效");
            map.put("code", "error");
            return map;
        }
        if (ObjectUtil.isEmpty(registerSaveDto.getLineCode())) {
            throw new BusinessException("条线编码不能为空");
        }
        //设置是预览调用
        registerSaveDto.setIsCasePreview(YesOrNoEnum.YES.getCode());
        String errorMsg = checkAndDealCaseRegisterInfo(registerSaveDto);
        if (StringUtils.isNotEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        String mainHandleSignPic = "";
        String assistHandleSignPic = "";
        for (CaseHandlePersonInfoDto handlePersonInfoDto : registerSaveDto.getHandlePersonInfoList()) {
            if (ObjectUtil.isNotEmpty(handlePersonInfoDto.getHandlePersonId())) {
                if (HandlePersonTypeEnum.MAIN.getCode().equals(handlePersonInfoDto.getHandlePersonType())) {
                    mainHandleSignPic = commonService.getHandleSignData(handlePersonInfoDto.getHandlePersonId());
                    handlePersonInfoDto.setDingId(handlePersonInfoDto.getDingId());
                } else {
                    assistHandleSignPic = commonService.getHandleSignData(handlePersonInfoDto.getHandlePersonId());
                }
            }
        }
        if (ObjectUtil.isNotEmpty(registerSaveDto.getPartiesLegalInfoList()) && registerSaveDto.getPartiesLegalInfoList().size() > 0) {
            registerSaveDto.setLegalInfoDto(registerSaveDto.getPartiesLegalInfoList().get(0));
        }
        //获取办案条线对应的领域
        LineDTO lineDTO = xzzfInterfaceService.getLineInfoByLineCode(registerSaveDto.getLineCode());
        //获取领域下业务参数
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        request.setApplyFieldCode(lineDTO.getTerritoryCode());
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        //获取流程信息--调用公用接口
        Map<String, Object> resultMap = configBusiParamMainService.getRelationWorkflowInfo(request);
        //业务参数Id
        String busiParamId = configBusiParamMainList.get(0).getId();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, "LASPB");

        StageDocCommonPreviewDto saveDto = new StageDocCommonPreviewDto();
        registerSaveDto.setOrgStandardName(commonService.getOrgStandardNameByOrgCode(userInfo.getOrgCode(), userInfo.getOrgCode()));
        saveDto.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        HashMap<String, Object> dataMap = BaseUtil.javaToMap(registerSaveDto);
        dataMap.put("mainHandleSignPic", mainHandleSignPic);
        dataMap.put("assistHandleSignPic", assistHandleSignPic);
        dataMap.put("signTime", BaseUtil.getNowDate());
        saveDto.setDataMap(dataMap);
        Map<String, Object> previewDocMap = stageDocCommonOperateService.genPreviewDoc(saveDto);
        String status = MapUtils.getString(previewDocMap, "success", "");
        if ("true".equals(status)) {
            map.put("msg", MapUtils.getString(previewDocMap, "msg", ""));
            map.put("code", "success");
            map.put("fileUrl", MapUtils.getString(previewDocMap, "pdfUrl", ""));
        } else {
            map.put("msg", MapUtils.getString(previewDocMap, "msg", ""));
            map.put("code", "error");
        }
        return map;
    }

    /**
     * 获取有执法证协办人员
     *
     * @return
     * @author lixj
     * @date 2022/5/6
     */
    @Override
    public List<HandleAssistVo> getAssistHandleList(String isContainLogin) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        JSONObject json = new JSONObject();
        UserDTO userDTO = UserUtil.getUserInfo();
        System.out.println(JSON.toJSONString(userDTO));
        System.out.println("++++++++++++++++++++" + userDTO.getUserId());
        String userId = userDTO.getUserId().toString();
        json.put("pageNum", 1);
        json.put("length", 999);
        List<String> deptList = new ArrayList<>();
        deptList.add(userDTO.getDeptCode());
        json.put("deptCodes", deptList);
        json.put("hasCert", Constant.STRING_1);
        //json.put("orgCode", userDTO.getOrgCode());
        List<String> orgCodes = new ArrayList<>();
        orgCodes.add(userDTO.getOrgCode());
        json.put("orgCodes", orgCodes);
        json.put("searchType", Constant.STRING_1);
        String param = json.toJSONString();
        String response = HttpUtil.createPost(url.concat(zfPeopleListUrl)).addHeaders(headers).body(param).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        // =============={"code":200,"data":{"total":9,"pages":1,"data":[{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"ssy13772230073","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"137****073","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1996-08-04","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 15:49:33","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"6d1491845afb477c9cd3f2986dc3bfd3","isValid":"1","updateTime":"2022-04-26 11:03:45","avatar":"","userId":"179071362599485440","realName":"史胜瑶","createBy":113854,"deleted":"0","createTime":"2022-04-26 11:03:45","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"trj13675896316","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"136****316","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1996-08-04","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-04-29 22:41:14","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"8af3ef28c9434a99971901a7cc8e1fb0","isValid":"1","updateTime":"2022-04-26 11:02:48","avatar":"","userId":"179071303626522624","realName":"田润家","createBy":113854,"deleted":"0","createTime":"2022-04-26 11:02:49","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"jjy16605755011","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"166****011","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1999-06-03","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 15:13:18","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"2d0b47279c8e460f9b24697024c5bbb7","isValid":"1","updateTime":"2022-04-26 11:01:44","avatar":"","userId":"179071235644194816","realName":"钱佳滢","createBy":113854,"deleted":"0","createTime":"2022-04-26 11:01:44","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"rm15382354535","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"153****535","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1996-05-09","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 16:44:48","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"1","oldUserId":"22f417430f714d2a9609852b6db4a1eb","isValid":"1","updateTime":"2022-04-26 10:57:59","avatar":"","userId":"179071000096276480","realName":"冉明","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:57:59","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"处罚检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"cyy17366371670","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"0","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477505","phone":"173****670","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1993-08-09","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"1","oldUserId":"3c31f40890da41ac94c24e890d1f38f0","isValid":"1","updateTime":"2022-04-26 10:56:59","avatar":"","userId":"179070937263505408","realName":"程亚运","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:56:59","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"lxj18758550527","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"187****527","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1998-06-05","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 16:48:33","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"1","oldUserId":"bcd8e123b9554bc1811020cee99c9ef6","isValid":"1","updateTime":"2022-04-26 10:55:54","avatar":"","userId":"179070869403860992","realName":"李细军","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:55:55","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"lyf18868876270","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"188****270","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1994-01-02","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 17:21:56","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"18c48d5a84b34071b48769864011a15f","isValid":"1","updateTime":"2022-04-26 10:54:42","avatar":"","userId":"179070793739665408","realName":"李亚锋","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:54:42","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"mlj18768164481","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"187****481","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1995-05-05","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-05 23:59:56","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"c6fd2bc65e6c4e47abc7ff1f1bf0a6ec","isValid":"1","updateTime":"2022-04-26 10:53:35","avatar":"","userId":"179070723748265984","realName":"毛仁杰","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:53:36","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"xyy18867145561","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"188****561","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1996-12-11","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 13:46:52","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"d3bf95d9d94347e9888bc69ec27b26d2","isValid":"1","updateTime":"2022-04-26 10:52:22","avatar":"","userId":"179070646307782656","realName":"项毓煜","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:52:22","isCurrentOrg":true,"dingDingId":" "}]},"message":"成功","errors":[]}
        List<HandleAssistVo> assistVoList = null;
        if (jsonObject.getIntValue("code") == 200) {
            JSONArray ja = jsonObject.getJSONObject("data").getJSONArray("data");
            if (ja == null || ja.size() == 0) {
                log.info("=======没有数据=======");
            }
            assistVoList = new ArrayList<>();
            for (int i = 0; i < ja.size(); i++) {
                JSONObject obj = (JSONObject) ja.get(i);
                /*String zfLicenseNo = xzzfInterfaceService.getLawEnforcementCertWithUserId(obj.getString("userId"));
                if (StringUtils.isEmpty(zfLicenseNo)) {
                    continue;
                }*/
                if (userId.equals(obj.getString("userId")) && Constant.STRING_0.equals(isContainLogin)) {
                    continue;
                }
                if (StringUtils.isNotBlank(obj.getString("realName"))) {
                    HandleAssistVo vo = new HandleAssistVo();
                    vo.setDeptName(obj.getString("deptName"));
                    vo.setLoginName(obj.getString("loginName"));
                    vo.setDingDingId(obj.getString("zwdAccountId"));
                    vo.setUserId(obj.getString("userId"));
                    vo.setRealName(obj.getString("realName"));
                    vo.setZfLicenseNo(obj.getString("zfCertNo"));
                    vo.setDeptCode(obj.getString("deptCode"));
                    vo.setOrgCode(obj.getString("orgCode"));
                    vo.setOrgName(obj.getString("orgName"));
                    vo.setPhone(obj.getString("phone"));
                    assistVoList.add(vo);
                }
            }
        }
        if (!ObjectUtils.isEmpty(assistVoList)) {
            //办案人员列表增加按姓名排序
            Collator china = Collator.getInstance(Locale.CHINA);
            Collections.sort(assistVoList, (o1, o2) -> china.compare(o1.getRealName(), o2.getRealName()));
        }
        return assistVoList;
    }

    /**
     * 获取有执法证协办人员
     *
     * @return
     * @author lixj
     * @date 2022/5/6
     */
    @Override
    public List<HandleAssistVo> getAssistHandleListByType(String type) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        JSONObject json = new JSONObject();
        UserDTO userDTO = UserUtil.getUserInfo();
        String userId = userDTO.getUserId().toString();
        json.put("pageNum", 1);
        json.put("length", 999);
        //json.put("orgCode", userDTO.getOrgCode());
        if (Constant.STRING_1.equals(type)) {
            List<String> orgCodes = new ArrayList<>();
            orgCodes.add(userDTO.getOrgCode());
            json.put("orgCodes", orgCodes);
            json.put("searchType", Constant.STRING_1);
        }
        if (Constant.STRING_2.equals(type)) {
            List<String> deptList = new ArrayList<>();
            deptList.add(userDTO.getDeptCode());
            json.put("deptCodes", deptList);
            json.put("hasCert", Constant.STRING_1);
        }
        String param = json.toJSONString();
        String response = HttpUtil.createPost(url.concat(zfPeopleListUrl)).addHeaders(headers).body(param).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        // =============={"code":200,"data":{"total":9,"pages":1,"data":[{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"ssy13772230073","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"137****073","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1996-08-04","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 15:49:33","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"6d1491845afb477c9cd3f2986dc3bfd3","isValid":"1","updateTime":"2022-04-26 11:03:45","avatar":"","userId":"179071362599485440","realName":"史胜瑶","createBy":113854,"deleted":"0","createTime":"2022-04-26 11:03:45","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"trj13675896316","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"136****316","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1996-08-04","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-04-29 22:41:14","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"8af3ef28c9434a99971901a7cc8e1fb0","isValid":"1","updateTime":"2022-04-26 11:02:48","avatar":"","userId":"179071303626522624","realName":"田润家","createBy":113854,"deleted":"0","createTime":"2022-04-26 11:02:49","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"jjy16605755011","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"166****011","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1999-06-03","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 15:13:18","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"2d0b47279c8e460f9b24697024c5bbb7","isValid":"1","updateTime":"2022-04-26 11:01:44","avatar":"","userId":"179071235644194816","realName":"钱佳滢","createBy":113854,"deleted":"0","createTime":"2022-04-26 11:01:44","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"rm15382354535","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"153****535","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1996-05-09","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 16:44:48","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"1","oldUserId":"22f417430f714d2a9609852b6db4a1eb","isValid":"1","updateTime":"2022-04-26 10:57:59","avatar":"","userId":"179071000096276480","realName":"冉明","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:57:59","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"处罚检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"cyy17366371670","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"0","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477505","phone":"173****670","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1993-08-09","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"1","oldUserId":"3c31f40890da41ac94c24e890d1f38f0","isValid":"1","updateTime":"2022-04-26 10:56:59","avatar":"","userId":"179070937263505408","realName":"程亚运","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:56:59","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"lxj18758550527","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"187****527","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1998-06-05","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 16:48:33","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"1","oldUserId":"bcd8e123b9554bc1811020cee99c9ef6","isValid":"1","updateTime":"2022-04-26 10:55:54","avatar":"","userId":"179070869403860992","realName":"李细军","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:55:55","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"lyf18868876270","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"188****270","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1994-01-02","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 17:21:56","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"18c48d5a84b34071b48769864011a15f","isValid":"1","updateTime":"2022-04-26 10:54:42","avatar":"","userId":"179070793739665408","realName":"李亚锋","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:54:42","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"mlj18768164481","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"187****481","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1995-05-05","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-05 23:59:56","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"c6fd2bc65e6c4e47abc7ff1f1bf0a6ec","isValid":"1","updateTime":"2022-04-26 10:53:35","avatar":"","userId":"179070723748265984","realName":"毛仁杰","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:53:36","isCurrentOrg":true,"dingDingId":" "},{"deptName":"台州市智慧城管中心","officeName":"","userNature":"","updateByName":"吴晨皓","suspendOrgCode":"","workContent":"执法检查","peropleCategory":"1","isAgent":"0","areaName":"台州市","loginName":"xyy18867145561","isDisabled":"","createByName":"吴晨皓","orgName":"台州市综合行政执法局","pcLoginFlag":"1","appLoginFlag":"1","isAdmin":"0","workContentRoleId":"176564108739477504","phone":"188****561","datasource":"2","position":"","deptCode":"3310000001208185","birthday":"1996-12-11","remark":"","isTemporary":"0","currentDeptName":"台州市智慧城管中心","particularType":"0","telPhone":"","currentDeptCode":"3310000001208185","identityType":"1","updateBy":113854,"orgCode":"331000000000_113310000026639221","pcLastLoginTime":"2022-05-06 13:46:52","currentOrgCode":"331000000000_113310000026639221","email":"","suspendDeptCode":"","sex":"2","oldUserId":"d3bf95d9d94347e9888bc69ec27b26d2","isValid":"1","updateTime":"2022-04-26 10:52:22","avatar":"","userId":"179070646307782656","realName":"项毓煜","createBy":113854,"deleted":"0","createTime":"2022-04-26 10:52:22","isCurrentOrg":true,"dingDingId":" "}]},"message":"成功","errors":[]}
        List<HandleAssistVo> assistVoList = null;
        if (jsonObject.getIntValue("code") == 200) {
            JSONArray ja = jsonObject.getJSONObject("data").getJSONArray("data");
            if (ja == null || ja.size() == 0) {
                log.info("=======没有数据=======");
            }
            assistVoList = new ArrayList<>();
            for (int i = 0; i < ja.size(); i++) {
                JSONObject obj = (JSONObject) ja.get(i);
//                if(userId.equals(obj.getString("userId"))){
//                    continue;
//                }
                HandleAssistVo vo = new HandleAssistVo();
                vo.setDeptName(obj.getString("deptName"));
                vo.setLoginName(obj.getString("loginName"));
                vo.setDingDingId(obj.getString("zwdAccountId"));
                vo.setUserId(obj.getString("userId"));
                vo.setRealName(obj.getString("realName"));
                vo.setZfLicenseNo(obj.getString("zfCertNo"));
                vo.setDeptCode(obj.getString("deptCode"));
                vo.setOrgCode(obj.getString("orgCode"));
                vo.setOrgName(obj.getString("orgName"));
                assistVoList.add(vo);
            }
        }
        return assistVoList;
    }


    /**
     * 获取下层机构信息
     *
     * @param orgCode
     * @return
     */
    @Override
    public List<CaseHandoutVo> getOrgListByTopOrg(String orgCode) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map<String, Object> map = new HashMap<>(4);
        map.put("orgCode", orgCode);
        String response = HttpUtil.createGet(url.concat(orgListByTopOrgUrl)).addHeaders(headers).form(map).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        List<CaseHandoutVo> CaseHandoutList = new ArrayList<>();
        if (jsonObject.getIntValue("code") == 200) {
            JSONArray ja = jsonObject.getJSONArray("data");
            if (ja == null || ja.size() == 0) {
                log.info("=======没有数据=======");
            }
            for (int i = 0; i < ja.size(); i++) {
                JSONObject obj = (JSONObject) ja.get(i);
                if (!obj.getString("orgCode").equals(UserUtil.getUserInfo().getOrgCode())) {
                    CaseHandoutVo caseHandoutVo = new CaseHandoutVo();
                    caseHandoutVo.setOrgCode(obj.getString("orgCode"));
                    caseHandoutVo.setOrgName(obj.getString("orgName"));
                    CaseHandoutList.add(caseHandoutVo);
                }
            }
        }
        // 获取派驻机构
        JSONObject json = new JSONObject();
        json.put("orgCode", orgCode);
        json.put("deptType", "2");
        json.put("pageNum", 1);
        json.put("length", 999);
        String res = HttpUtil.createPost(url.concat(deptListByTopOrgUrl)).addHeaders(headers).body(json.toJSONString()).execute().body();
        JSONObject deptJsonObject = JSONObject.parseObject(res);
        if (deptJsonObject.getIntValue("code") == 200) {
            JSONArray ja = deptJsonObject.getJSONObject("data").getJSONArray("data");
            if (ja == null || ja.size() == 0) {
                log.info("=======没有数据=======");
            }
            if (!ObjectUtils.isEmpty(ja)) {
                for (int i = 0; i < ja.size(); i++) {
                    JSONObject obj = (JSONObject) ja.get(i);
                    CaseHandoutVo caseHandoutVo = new CaseHandoutVo();
                    caseHandoutVo.setOrgCode(obj.getString("deptCode"));
                    caseHandoutVo.setOrgName(obj.getString("deptName"));
                    CaseHandoutList.add(caseHandoutVo);
                }
            }
        }
        return CaseHandoutList;
    }

    /**
     * 【V2.0.0】描述：保存立案登记
     *
     * @param saveDto 保存dto
     * @return {@link CaseRegisterSaveVo }
     * @author shishengyao
     * @date 2022/05/10
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CaseRegisterSaveVo saveCaseRegister(CaseRegisterSaveDto saveDto) {
        //先删除已保存的立案审批表 然后插入历史 解决切换条线后 立案审批表目录编码不一样问题
        if (StringUtils.isNotBlank(saveDto.getCaseId())) {
            // 处理历史立案审批表
            handleHisCaseRegister(saveDto);
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        //校验参数并处理数据
        String errorMsg = checkAndDealCaseRegisterInfo(saveDto);
        if (StringUtils.isNotEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        // 获取抬头
        assembleOrgStandarName(saveDto, userInfo);
        //获取办案条线对应的领域
        assembleLineCode(saveDto);
        //获取领域下业务参数
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        request.setApplyFieldCode(saveDto.getCaseTerritoryCode());
        String busiParamId = getBusiParamId(request);
        saveDto.setBusiParamId(busiParamId);
        //获取流程信息--调用公用接口
        request.setCaseType(saveDto.getCaseType());
        Map<String, Object> resultMap = configBusiParamMainService.getRelationWorkflowInfo(request);
        //速结告知书处理
        dealCaseDocumentRecordWithFastCase(saveDto);
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, "LASPB");
        String workFlowCode = resultMap.get("WORKFLOWCODE").toString();
        List<CaseReasonMainRecord> caseReasonMainRecords = new ArrayList<>();
        List<CasePartiesRecord> partiesRecords = new ArrayList<>();
        //1、处理立案登记-主表、宽表信息 内部方法普通调用时代理不生效，使用@EnableAspectJAutoProxy开启自动代理
        ((CaseRegisterServiceImpl) AopContext.currentProxy()).dealCaseRegisterMainInfo(saveDto, workFlowCode, userInfo);
        String caseId = saveDto.getCaseId();
        // 非人社还走以前流程。
        if (!Constant.HUMAN_SOCIETY_BARS_CODE.equals(saveDto.getLineCode().substring(0, 4))) {
            //2、处理案由信息
            dealCaseRegisterCaseReasonInfo(saveDto.getCaseReasonInfoList(), caseId, caseReasonMainRecords);
        }
        //3、处理办案人员信息
        dealCaseRegisterHandlePersonInfo(saveDto.getHandlePersonInfoList(), caseId, userInfo);
        //4、处理当事人信息
        ((CaseRegisterServiceImpl) AopContext.currentProxy()).dealCaseRegisterPartiesInfo(saveDto, workFlowCode, partiesRecords);
        //5、处理附件
        dealCaseRegisterAppendixInfo(saveDto, configBusiParamDocumentInfo.getDocumentCatalogCode());
        //6、处理案件详情补充表
        dealCaseRegisterAuxiliaryInfo(saveDto, caseReasonMainRecords, partiesRecords);
        //7、处理关联文书
        dealCaseRegisterRelatedDocumentInfo(saveDto);
        //8.调用文书公共接口生成文书记录
        generateDocument(saveDto, configBusiParamDocumentInfo, userInfo);
        //如果是速结程序，并且存在知情同意告知书，则需要更新文书记录表中的partyId（立案更新时，会删除之前的当事人，重新新增）
        this.updateFastNoticeDocumentPartyId(saveDto, userInfo);
        //如果是案件转换执行的保存，则需要清除临时数据
        if (AppCaseConvertTemporaryEnum.NORMAL_CONVERT.equals(saveDto.getConvertFlag())) {
            appCaseConvertTemporaryRecordService.removeCurrentUserConvertTemporaryRecord(saveDto.getConvertFlag());
        }
        return assembleVo(saveDto, configBusiParamDocumentInfo);
    }

    private void assembleOrgStandarName(CaseRegisterSaveDto saveDto, UserDTO userInfo) {
        if (!ObjectUtil.isEmpty(saveDto.getOrgStandardName())) {
            return;
        }
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userInfo.getOrgCode(), userInfo.getDeptCode());
        if (ObjectUtil.isEmpty(sysDepartParam.getOrgStandardName())) {
            throw new BusinessException("办案单位暂未维护文书抬头");
        }
        saveDto.setOrgStandardName(sysDepartParam.getOrgStandardName());
    }


    /**
     * 组装返回参数
     */
    private static CaseRegisterSaveVo assembleVo(CaseRegisterSaveDto saveDto, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        CaseRegisterSaveVo saveVo = new CaseRegisterSaveVo();
        saveVo.setCaseId(saveDto.getCaseId());
        saveVo.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        return saveVo;
    }

    /**
     * 获取业务参数id
     *
     * @param request
     * @return
     */
    private String getBusiParamId(RelationWorkflowInfoRequest request) {
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        if (CollUtil.isEmpty(configBusiParamMainList)) {
            throw new BusinessException("未匹配业务参数信息列表");
        }
        ConfigBusiParamMain configBusiParamMain = configBusiParamMainList.stream().findFirst().orElse(null);
        if (Objects.isNull(configBusiParamMain)) {
            throw new BusinessException("未匹配业务参数信息");
        }
        //业务参数Id
        String busiParamId = configBusiParamMain.getId();
        return busiParamId;
    }

    /**
     * 生成文书
     *
     * @param saveDto
     * @param configBusiParamDocumentInfo
     * @param userInfo
     */
    private void generateDocument(CaseRegisterSaveDto saveDto, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo, UserDTO userInfo) {
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        commonOperateSaveDto.setCaseId(saveDto.getCaseId());
        commonOperateSaveDto.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        commonOperateSaveDto.setIsUpdateRelationTable(Constant.STRING_0);
        commonOperateSaveDto.setPartyId(saveDto.getPartyIds());
        saveDto.setOrgStandardName(commonService.getOrgStandardNameByOrgCode(userInfo.getOrgCode(), userInfo.getDeptCode()));
        commonOperateSaveDto.setDataMap(BaseUtil.javaToMap(saveDto));
        log.info("----------进入文书生成公共服务saveDocInfo--------------");
        Map<String, Object> docResultMap = stageDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
        String status = MapUtils.getString(docResultMap, "success", "");
        String msg = MapUtils.getString(docResultMap, "msg", "");
        if (!"true".equals(status)) {
            log.info("----------文书生成公共服务saveDocInfo------报错---" + docResultMap);
            throw new BusinessException(msg);
        }
    }

    /**
     * 获取办案条线对应的领域
     *
     * @param saveDto
     */
    private void assembleLineCode(CaseRegisterSaveDto saveDto) {
        LineDTO lineDTO = xzzfInterfaceService.getLineInfoByLineCode(saveDto.getLineCode());
        saveDto.setCaseTerritoryCode(lineDTO.getTerritoryCode());
        saveDto.setCaseTerritoryName(lineDTO.getTerritoryName());
    }

    /**
     * 先删除已保存的立案审批表 然后插入历史 解决切换条线后 立案审批表目录编码不一样问题
     */
    private void handleHisCaseRegister(CaseRegisterSaveDto saveDto) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        if (!ObjectUtils.isEmpty(caseMainInfo) && StringUtils.isNotBlank(caseMainInfo.getCaseNumber())) {
            throw new BusinessException("该案件已经立案通过，不能再次立案登记");
        }
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", saveDto.getCaseId())
                .andLike("documentCatalogCode", "%" + DocumentKindEnum.DOC_KIND_LASPB.getCode() + "%");
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseDocumentRecords)) {
            for (CaseDocumentRecord caseDocumentRecord : caseDocumentRecords) {
                //添加历史
                CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
                BeanUtils.copyProperties(caseDocumentRecord, caseDocumentRecordHis);
                caseDocumentRecordHis.setId(com.icinfo.framework.tools.utils.StringUtils.uuid());
                caseDocumentRecordHis.setRecordId(caseDocumentRecord.getId());
                caseDocumentRecordHis.setOp("update");
                caseDocumentRecordHis.setHisCreateTime(new Date());
                caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);
                //删除
                caseDocumentRecordMapper.deleteByPrimaryKey(caseDocumentRecord.getId());
            }
        }
    }

    /**
     * 速结告知书处理
     *
     * @param saveDto
     */
    private void dealCaseDocumentRecordWithFastCase(CaseRegisterSaveDto saveDto) {
        //查询案件信息
        if (ObjectUtil.isEmpty(saveDto.getCaseId())) {
            return;
        }

        //先删除一下快办通知书
        Example example = new Example(ConfigBusiParamDocumentInfo.class);
        example.createCriteria().andIn("documentKindCode", Arrays.asList(DocumentKindEnum.DOC_KIND_DK2SJCXGZS.getCode(), DocumentKindEnum.DOC_KIND_DK2JAKBTZS.getCode()));
        List<ConfigBusiParamDocumentInfo> configBusiParamMainList = configBusiParamDocumentInfoMapper.selectByExample(example);
        if (ObjectUtil.isNotEmpty(configBusiParamMainList)) {
            for (ConfigBusiParamDocumentInfo configBusiParamDocumentInfo : configBusiParamMainList) {
                Example dExample = new Example(CaseDocumentRecord.class);
                dExample.createCriteria().andEqualTo("caseId", saveDto.getCaseId())
                        .andEqualTo("documentCatalogCode", configBusiParamDocumentInfo.getDocumentCatalogCode());
                List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(dExample);
                if (!ObjectUtils.isEmpty(caseDocumentRecords)) {
                    for (CaseDocumentRecord caseDocumentRecord : caseDocumentRecords) {
                        //文书已签字确认则不处理
                        if (!DocumentStatusEnum.CONFIRM_END.getCode().equals(caseDocumentRecord.getDocumentSignstampedStatus())) {
                            //添加历史
                            CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
                            BeanUtils.copyProperties(caseDocumentRecord, caseDocumentRecordHis);
                            caseDocumentRecordHis.setId(com.icinfo.framework.tools.utils.StringUtils.uuid());
                            caseDocumentRecordHis.setRecordId(caseDocumentRecord.getId());
                            caseDocumentRecordHis.setOp("update");
                            caseDocumentRecordHis.setHisCreateTime(new Date());
                            caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);
                            //删除
                            caseDocumentRecordMapper.deleteByPrimaryKey(caseDocumentRecord.getId());
                        }
                    }
                }
            }
        }

        /*CaseMainInfo oldCaseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        if (ObjectUtil.isEmpty(oldCaseMainInfo) || ObjectUtil.isEmpty(oldCaseMainInfo.getCaseType())) {
            //原来没有确定案件类型,不做处理
            return;
        }

        if(saveDto.getCaseType().equals(oldCaseMainInfo.getCaseType())){
            return;
        }
        //获取速结或快办文书目录编码
        String documentCatalogCodeOfSJGZS = caseDocumentRecordService.getDocumentCatalogCodeOfSJGZS(userInfo.getAreaCode(), saveDto.getBusiParamId());

        //如果速结告知书没签字, 则删除文书
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", saveDto.getCaseId())
                .andEqualTo("documentCatalogCode", documentCatalogCodeOfSJGZS);
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseDocumentRecords)) {
            for (CaseDocumentRecord caseDocumentRecord : caseDocumentRecords) {
                //文书已签字确认则不处理
                if (!DocumentStatusEnum.CONFIRM_END.getCode().equals(caseDocumentRecord.getDocumentSignstampedStatus())) {
                    //添加历史
                    CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
                    BeanUtils.copyProperties(caseDocumentRecord, caseDocumentRecordHis);
                    caseDocumentRecordHis.setId(com.icinfo.framework.tools.utils.StringUtils.uuid());
                    caseDocumentRecordHis.setRecordId(caseDocumentRecord.getId());
                    caseDocumentRecordHis.setOp("update");
                    caseDocumentRecordHis.setHisCreateTime(new Date());
                    caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);
                    //删除
                    caseDocumentRecordMapper.deleteByPrimaryKey(caseDocumentRecord.getId());
                }
            }
        }*/
    }

    /**
     * 如果是速结程序，并且存在知情同意告知书，则需要更新文书记录表中的partyId（立案更新时，会删除之前的当事人，重新新增）
     */
    private void updateFastNoticeDocumentPartyId(CaseRegisterSaveDto saveDto, UserDTO userInfo) {
        if (!CaseTypeEnum.SIMPLE_QUICK.getCode().equals(saveDto.getCaseType())) {
            return;
        }
        // 查询业务关联文书配置
        String documentCatalogCodeOfSJGZS = caseDocumentRecordService.getDocumentCatalogCodeOfSJGZS(userInfo.getAreaCode(), saveDto.getBusiParamId());
        /*ConfigBusiParamDocumentInfo configBusiParam = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(saveDto.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK2SJCXGZS.getCode());
        if(configBusiParam == null){
            throw new BusinessException("速结程序知情同意书配置不存在");
        }*/
        //获取知同意书文书记录
        CaseDocumentRecord record = caseDocumentRecordService.getCaseDocumentRecord(saveDto.getCaseId(), documentCatalogCodeOfSJGZS);
        if (record == null) {
            return;
        }
        //获取当事人，并更新
        List<CasePartiesRecordVo> list = casePartiesRecordService.getCasePartiesInfo(saveDto.getCaseId());
        if (list != null && list.size() > 0) {
            record.setPartyId(list.get(0).getPartyId());
            caseDocumentRecordMapper.updateByPrimaryKey(record);
        }
    }

    /**
     * 判断案件是否重复提交了 true 重复了，false 没有重复
     *
     * @param caseMainInfoDto
     * @return boolean
     * @author lxj
     * @date 2022/3/5
     **/
    private boolean checkCaseExist(CaseMainInfoDto caseMainInfoDto) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("caseReason", caseMainInfoDto.getCaseReason());
        map.put("happenTime", caseMainInfoDto.getHappenTime());
        List<String> caseIdList = caseMainDetailInfoMapper.selectCaseIdByReasonAndTime(map);
        if (caseIdList == null || caseIdList.size() == 0) {
            return false;
        }
        for (int i = 0; i < caseIdList.size(); i++) {
            Example example = new Example(CasePartiesRecord.class);
            String caseId = caseIdList.get(i);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1);
            List<CasePartiesRecordVo> recordList = casePartiesRecordService.getCasePartiesInfo(caseId);
            //判断个人还是企业
            if (Constant.STRING_1.equals(recordList.get(0).getPartyType())) {
                if (recordList.get(0).getPartyIdentityCode().equals(caseMainInfoDto.getCertNo())) {
                    if (caseIdList.get(i).equals(caseMainInfoDto.getCaseId())) {
                        continue;
                    }
                    return true;
                }
            } else if (Constant.STRING_2.equals(recordList.get(0).getPartyType())) {
                if (recordList.get(0).getPartyIdentityCode().equals(caseMainInfoDto.getUniscid())) {
                    if (caseIdList.get(i).equals(caseMainInfoDto.getCaseId())) {
                        continue;
                    }
                    return true;
                }
            }
        }
        // “案发日期+案由+当事人证件号”或“案发日期+案由+统一社会信用代码”在系统中已存在，则提示用户“案件信息已存在，请勿重复录入！”。
        return false;
    }


    /**
     * 手动或者未传企业当事人法人身份证时，在调用一次法人库获取信息；
     *
     * @param uniscid 统一代码
     * @param company 公司名称
     * @return String
     */
    private String getFrCertNo(String uniscid, String company) {
        if (StringUtils.isEmpty(uniscid) && StringUtils.isEmpty(company)) {
            return "";
        }
        JSONArray array = commonService.getCompanyMsg(uniscid, company);
        if (array == null || array.size() == 0) {
            return "";
        } else if (array.size() == 1) {
            JSONObject obj = (JSONObject) array.get(0);
            return obj.getString("fr_zjhm");
        } else {
            return "";
        }

    }


    /*
     * 更新案件编号实现方法
     */
    @Override
    public String doCaseStageOperate(String caseId, String catalogCode) {

        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, catalogCode);
        if (caseDocumentRecord == null) {
            return "未指定案件id";
        }
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(caseMainInfo.getCaseType())
                || CaseTypeEnum.FAST_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
            //简案快办获取立案审批表文书
            caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, DocumentKindEnum.DOC_KIND_LASPB.getCode());
        }
        caseMainInfo.setCaseNumber(caseDocumentRecord.getDocumentNumber());
        caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);
        return Constant.STRING_SUCCESS_EN;
    }

    /**
     * 【V2.0.0】校验立案登记信息
     *
     * @param saveDto 保存dto
     * @return {@link String }
     * @author shishengyao
     * @date 2022/05/10
     */
    @Override
    public String checkAndDealCaseRegisterInfo(CaseRegisterSaveDto saveDto) {
        String errorMessage = "";
         /*
        1	巡查中发现
        2	社会举报
        3	有关部门移送
        4	上级行政机关交办
        5	下级行政机关报请
        6	非现场执法
        7	机构检测报告*/
        //案源是有关部门移送 时，校验参数
        if (CaseSourceEnum.CASE_SOURCE_YGBMYS.getCode().equals(saveDto.getCaseSourceId())) {
            if (ObjectUtil.isEmpty(saveDto.getTransferUnit())) {
                errorMessage = "移送单位不能为空";
            } else if (ObjectUtil.isEmpty(saveDto.getTransferPerson())) {
                errorMessage = "移送人不能为空";
            } else if (ObjectUtil.isEmpty(saveDto.getTransferPhone())) {
                errorMessage = "移送人手机号不能为空";
            } else if (ObjectUtil.isEmpty(saveDto.getTransferUnitUniscid())) {
                errorMessage = "未匹配到移送单位" + saveDto.getTransferUnit() + "统一社会信用代码信息，请联系管理员";
            }
        } else if (CaseSourceEnum.CASE_SOURCE_ZXZJCZFX.getCode().equals(saveDto.getCaseSourceId())) {
            //预览调用不校验
            if (!YesOrNoEnum.YES.getCode().equals(saveDto.getIsCasePreview())) {
                //在行政检查中发现时检验是否是检查转立案
                String caseSourceRegisterId = saveDto.getCaseId();
                if (ObjectUtils.isEmpty(caseSourceRegisterId)) {
                    caseSourceRegisterId = saveDto.getCaseSourceRegisterId();
                }
                if (ObjectUtils.isEmpty(caseSourceRegisterId)) {
                    return "非检查转立案,案件来源不能使用在行政检查中发现";
                }
                CaseSourceRegisterDetailInfo detailInfo = caseSourceRegisterDetailInfoMapper.selectByPrimaryKey(caseSourceRegisterId);
                if (ObjectUtils.isEmpty(detailInfo)) {
                    return "非检查转立案,案件来源不能使用在行政检查中发现";
                }
            }
        }
        if (ObjectUtil.isEmpty(saveDto.getLineCode()) || ObjectUtil.isEmpty(saveDto.getLineName())) {
            return "未匹配到办案条线信息，请联系管理员";
        }

        //法人当事人数量
        int partiesLegalCount = ObjectUtil.isEmpty(saveDto.getPartiesLegalInfoList()) ? 0 : saveDto.getPartiesLegalInfoList().size();
        //个人当事人数量
        int partiesPersonCount = ObjectUtil.isEmpty(saveDto.getPartiesPersonInfoList()) ? 0 : saveDto.getPartiesPersonInfoList().size();
        //当事人总数
        int partiesCount = partiesLegalCount + partiesPersonCount;
        // 这里判断是案由还是处罚事项
        //案由
        //int caseReasonCount = saveDto.getCaseReasonInfoList().size();
        //2、校验当事人信息
        if (partiesLegalCount > 1) {
            errorMessage = "企业当事人只能有一个";
            return errorMessage;
        }
        if (partiesCount < 1) {
            errorMessage = "必须选择至少一个当事人";
            return errorMessage;
        } else if (partiesCount > 10) {
            errorMessage = "当事人不能超过10个";
            return errorMessage;
        }
        //如果是速结程序，则只能有一个当事人
        if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(saveDto.getCaseType()) && partiesCount != 1) {
            errorMessage = "速结程序只能有一个当事人";
            return errorMessage;
        }
        //如果是速结程序，条线校验
        //速结程序暂时只支持综合执法和乡镇街道条线
        List simpleQuickAllowLineList = Arrays.asList(TerritoryCodeEnum.ZHZF.getCode(), TerritoryCodeEnum.XZJD.getCode());
        String selectTerritoryCode = saveDto.getLineCode().substring(0, 4);
        if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(saveDto.getCaseType())
                && !simpleQuickAllowLineList.contains(selectTerritoryCode)) {
            errorMessage = "该条线不支持速结程序";
            return errorMessage;
        }
        int caseReasonCount;
        if (!Constant.HUMAN_SOCIETY_BARS_CODE.equals(saveDto.getLineCode().substring(0, 4))) {
            caseReasonCount = saveDto.getCaseReasonInfoList().size();
            //3、多案由校验 当事人
            if (saveDto.getCaseReasonInfoList().size() > 1) {
                if (partiesCount > 1) {
                    errorMessage = "选择多个案由时，只能选择一个当事人";
                    return errorMessage;
                }
            }
        } else {
            caseReasonCount = saveDto.getPersonReasonIds().size();
            //3、多案由校验 当事人
            if (caseReasonCount > 1) {
                if (partiesCount > 1) {
                    errorMessage = "选择多个案由时，只能选择一个当事人";
                    return errorMessage;
                }
            }
        }

        List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoForPdfList = new ArrayList<>();

        //4、校验法人当事人信息的合法性
        List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoDtos = saveDto.getPartiesLegalInfoList();
        if (partiesLegalCount > 0) {
            List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoForPdfList = new ArrayList<>();
            for (CaseRegisterPartiesLegalInfoDto legalInfoDto : partiesLegalInfoDtos) {
                CustomCheckParamUtil.doCheck(legalInfoDto);
                if (!SocialCreditCodeUtil.isValidEntCode(legalInfoDto.getUniscid(), legalInfoDto.getEntType())) {
                    return "统一社会信用代码：" + legalInfoDto.getUniscid() + "不符合规范";
                }
                if (saveDto.getLineCode().contains(TerritoryCodeEnum.NYNC.getCode())
                        && EnterTypeEnum.PRIVATELY_BUSINESS.getCode().equals(legalInfoDto.getEntType())) {
                    //农业农村个体工商户信息放在个人列表中
                    String certType = CertTypeEnum.getValueByCode(legalInfoDto.getLegalCertType());
                    CaseRegisterPartiesPersonInfoDto partiesPersonInfoForPdf = new CaseRegisterPartiesPersonInfoDto();
                    partiesPersonInfoForPdf.setCertTypeAndCertNo(certType + " " + legalInfoDto.getLegalCertNo());
                    partiesPersonInfoForPdf.setCertNo(legalInfoDto.getLegalCertNo());
                    partiesPersonInfoForPdf.setBirthStr("/");
                    partiesPersonInfoForPdf.setSex("/");
                    partiesPersonInfoForPdf.setNationality("/");
                    partiesPersonInfoForPdf.setAddress(legalInfoDto.getUnitAddress());
                    partiesPersonInfoForPdf.setName(legalInfoDto.getLegal());
                    partiesPersonInfoForPdf.setMobile(ObjectUtils.isEmpty(legalInfoDto.getPhone()) ? "/" : legalInfoDto.getPhone());
                    partiesPersonInfoForPdf.setUnitName(legalInfoDto.getEntName());
                    partiesPersonInfoForPdf.setPostCode(BaseUtil.transferNullToSlash(legalInfoDto.getPostCode()));
                    partiesPersonInfoForPdf.setCompanyName(legalInfoDto.getEntName());
                    partiesPersonInfoForPdf.setUniscid(ObjectUtils.isEmpty(legalInfoDto.getUniscid()) ? "/" : legalInfoDto.getUniscid());
                    String workAndJob = legalInfoDto.getEntName() + (ObjectUtils.isEmpty(legalInfoDto.getJob()) ? "" : " " + legalInfoDto.getJob());
                    partiesPersonInfoForPdf.setUnitNameAndJob(workAndJob);

                    partiesPersonInfoForPdfList.add(partiesPersonInfoForPdf);
                } else {
                    CaseRegisterPartiesLegalInfoDto partiesLegalInfoDto = new CaseRegisterPartiesLegalInfoDto();
                    BeanUtils.copyProperties(legalInfoDto, partiesLegalInfoDto);
                    partiesLegalInfoDto.setPhone(ObjectUtils.isEmpty(legalInfoDto.getPhone()) ? "/" : legalInfoDto.getPhone());
                    partiesLegalInfoDto.setJob(ObjectUtils.isEmpty(legalInfoDto.getJob()) ? "/" : legalInfoDto.getJob());
                    partiesLegalInfoDto.setLegalCertNo(ObjectUtils.isEmpty(legalInfoDto.getLegalCertNo()) ? "/" : legalInfoDto.getLegalCertNo());
                    partiesLegalInfoDto.setPostCode(BaseUtil.transferNullToSlash(partiesLegalInfoDto.getPostCode()));
                    // 应急条线参数设置
                    // 当事人基本情况：统一社会信用代码：【统一社会信用代码值】，法定发表人或负责人：【法定发表人或负责人值】
                    // 例：统一社会信用：1321231321，法定代表人：张三
                    String partyBasicInfo = "统一社会信用：" + legalInfoDto.getUniscid() + "，法定代表人：" + legalInfoDto.getLegal();
                    legalInfoDto.setPartyBasicInfo(partyBasicInfo);
                    partiesLegalInfoDto.setPartyBasicInfo(partyBasicInfo);
                    partiesLegalInfoForPdfList.add(partiesLegalInfoDto);
                }

            }
            saveDto.setLegalInfoDto(partiesLegalInfoDtos.get(0));
            saveDto.setPartiesLegalInfoForPdfList(partiesLegalInfoForPdfList);

        }

        //5、校验个人当事人信息的合法性
        List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoList = saveDto.getPartiesPersonInfoList();
        if (partiesPersonCount > 0) {
            //判断是否有重复用户
            Map<Object, Long> personInfoCollect = partiesPersonInfoList.stream().collect(
                    Collectors.groupingBy(CaseRegisterPartiesPersonInfoDto::getCertNo, Collectors.counting()));
            List<Object> repeatCertNos = personInfoCollect.keySet().stream().
                    filter(key -> personInfoCollect.get(key) > 1).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(repeatCertNos) && repeatCertNos.size() > 0) {
                String collect = repeatCertNos.stream().map(e -> e.toString()).collect(Collectors.joining(","));
                errorMessage = "当事人证件号" + collect + "重复";
                return errorMessage;
            }

            //List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoForPdfList = new ArrayList<>();
            for (CaseRegisterPartiesPersonInfoDto personInfoDto : partiesPersonInfoList) {
                CustomCheckParamUtil.doCheck(personInfoDto);
                //校验身份证是否合法
                if (StringUtils.isNotEmpty(personInfoDto.getCertNo()) && personInfoDto.getCertType().equals("SFZ")) {
                    boolean flag = commonService.checkRealNameDifferent(personInfoDto.getCertNo(), personInfoDto.getName());
                    if (flag) {
                        errorMessage = "当事人" + personInfoDto.getName() + "证件号码和姓名不匹配";
                        return errorMessage;
                    }
                }
                String certType = CertTypeEnum.getValueByCode(personInfoDto.getCertType());
                personInfoDto.setCertTypeAndCertNo(certType + " " + personInfoDto.getCertNo());
                personInfoDto.setCertTypeName(certType);
                personInfoDto.setBirthStr(BaseUtil.getFormatDate(personInfoDto.getBirth()));
                CaseRegisterPartiesPersonInfoDto partiesPersonInfoForPdf = new CaseRegisterPartiesPersonInfoDto();
                BeanUtils.copyProperties(personInfoDto, partiesPersonInfoForPdf);
                partiesPersonInfoForPdf.setMobile(ObjectUtils.isEmpty(personInfoDto.getMobile()) ? "/" : personInfoDto.getMobile());
                partiesPersonInfoForPdf.setUnitName(ObjectUtils.isEmpty(personInfoDto.getUnitName()) ? "/" : personInfoDto.getUnitName());
                partiesPersonInfoForPdf.setPostCode(BaseUtil.transferNullToSlash(personInfoDto.getPostCode()));
                // 应急条线参数设置
                // 当事人基本情况：性别：【性别值】，出生日期：【出生日期值】，【身份证件类型】号码：【身份证件号码】
                // 例：性别：男，出生日期：2022年9月5日，公民身份证号码：1231231，住址：天津市河西区423123123
                String partyBasicInfo = "性别：" + personInfoDto.getSex() + "，出生日期：" + personInfoDto.getBirthStr() +
                        "，公民身份证号码：" + personInfoDto.getCertNo() + "，住址：" + personInfoDto.getAddress();
                personInfoDto.setPartyBasicInfo(partyBasicInfo);
                partiesPersonInfoForPdf.setPartyBasicInfo(partyBasicInfo);
                partiesPersonInfoForPdf.setCompanyName("/");
                partiesPersonInfoForPdf.setUniscid("/");
                if (ObjectUtils.isEmpty(personInfoDto.getUnitName())) {
                    partiesPersonInfoForPdf.setUnitNameAndJob("/");
                } else {
                    partiesPersonInfoForPdf.setUnitNameAndJob(personInfoDto.getUnitName());
                }

                partiesPersonInfoForPdfList.add(partiesPersonInfoForPdf);
            }
            //saveDto.setPartiesPersonInfoForPdfList(partiesPersonInfoForPdfList);
        }
        saveDto.setPartiesPersonInfoForPdfList(partiesPersonInfoForPdfList);
        // 处理添加：案件案由、当事人类型 ; 处罚方式
        saveDto.setPartiesCount(partiesCount);
        saveDto.setCaseReasonCount(saveDto.getCaseReasonCount());
        String casePartiesReasonType = "";
        String handleType = "";
        if (!Constant.HUMAN_SOCIETY_BARS_CODE.equals(saveDto.getLineCode().substring(0, 4))) {
            if (caseReasonCount == 1 && partiesCount == 1) {
                casePartiesReasonType = PartiesReasonTypeEnum.SINGLE_PARTY.getCode();
                handleType = HandleTypeEnum.NORMAL_PUNISH.getCode();
            } else if (caseReasonCount == 1 && saveDto.getPartiesCount() > 1) {
                casePartiesReasonType = PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode();
            } else if (caseReasonCount > 1 && partiesCount == 1) {
                casePartiesReasonType = PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode();
                handleType = HandleTypeEnum.MERGE_PUNISH.getCode();
            }
        } else {
            // 人社条线只区分多当事人和单当事人不和人社案由关联
            if (partiesCount == 1) {
                casePartiesReasonType = PartiesReasonTypeEnum.SINGLE_PARTY.getCode();
            } else if (partiesCount > 1) {
                casePartiesReasonType = PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode();
            }
        }
        if (!ObjectUtils.isEmpty(saveDto.getCaseHappenTime())) {
            saveDto.setCaseHappenTimeStr(DateTimeFormatter.ofPattern("yyyy年M月d日").format(BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime())));
        }

        //应急案由名称处理
        if (!ObjectUtils.isEmpty(saveDto.getCaseEmergencyReasonList())) {
            List<CaseEmergencyReasonInfoDto> caseEmergencyReasonList = saveDto.getCaseEmergencyReasonList();
            //应急案由处理
            String caseEmergencyReasonName = caseEmergencyReasonList.get(0).getEmergencyReasonName();
            if (caseEmergencyReasonList.size() > 1) {
                caseEmergencyReasonName += "等";
            }
            saveDto.setCaseEmergencyReasonName(caseEmergencyReasonName);
        }

        saveDto.setHandleType(handleType);
        saveDto.setCasePartiesReasonType(casePartiesReasonType);
        return errorMessage;
    }

    /**
     * 描述：1、处理立案主表、宽表主要信息
     *
     * @author shishengyao
     * @date 2022/05/18
     */
    @WorkFlowRollAnnotation //private方法注解不生效，所以改为public
    public Map<String, Object> dealCaseRegisterMainInfo(CaseRegisterSaveDto saveDto, String workFlowCode, UserDTO userInfo) {
        LocalDateTime nowDate = LocalDateTime.now();
        // 组装主表数据
        CaseMainInfo caseMainInfo = new CaseMainInfo();
        BeanUtils.copyProperties(saveDto, caseMainInfo);
        caseMainInfo.setCaseStatus(CaseStatusEnum.CASE_REGISTER.getCode());
        caseMainInfo.setCaseName(saveDto.getCaseName());
        caseMainInfo.setHandleType(saveDto.getHandleType());
        caseMainInfo.setCasePartiesReasonType(saveDto.getCasePartiesReasonType());
        caseMainInfo.setCaseOrgCode(userInfo.getOrgCode());
        caseMainInfo.setCaseOrgName(userInfo.getOrgName());
        caseMainInfo.setCaseDeptCode(userInfo.getDeptCode());
        caseMainInfo.setCaseDeptName(userInfo.getDeptName());
        caseMainInfo.setCaseAreaCode(userInfo.getAreaCode());
        caseMainInfo.setLineCode(saveDto.getLineCode());
        caseMainInfo.setLineName(saveDto.getLineName());
        caseMainInfo.setBusiParamId(saveDto.getBusiParamId());
        caseMainInfo.setCaseTerritoryCode(saveDto.getCaseTerritoryCode());
        caseMainInfo.setCaseTerritoryName(saveDto.getCaseTerritoryName());
        //添加部门全称、部门统一信用代码
        caseMainInfo.setCaseOrgFullName(userInfo.getOrgFullName());
        caseMainInfo.setUnicode(userInfo.getUnicode());
        //非简案快办 设置案件类型--普通程序
        if (!CaseTypeEnum.SIMPLE_QUICK.getCode().equals(saveDto.getCaseType())
                && !CaseTypeEnum.FAST_PROCEDURE.getCode().equals(saveDto.getCaseType())) {
            caseMainInfo.setCaseType(CaseTypeEnum.NORMAL_PROCEDURE.getCode());
        }

        //设置主办协办人员信息
        List<CaseHandlePersonInfoDto> handlePersonInfoList = saveDto.getHandlePersonInfoList();
        if (ObjectUtil.isNotEmpty(handlePersonInfoList)) {
            for (CaseHandlePersonInfoDto caseHandlePersonInfoDto : handlePersonInfoList) {
                if (HandlePersonTypeEnum.MAIN.getCode().equals(caseHandlePersonInfoDto.getHandlePersonType())) {
                    caseMainInfo.setHandlePersonMainId(caseHandlePersonInfoDto.getHandlePersonId());
                    caseMainInfo.setHandlePersonMainName(caseHandlePersonInfoDto.getHandlePersonName());
                } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(caseHandlePersonInfoDto.getHandlePersonType())) {
                    caseMainInfo.setHandlePersonAssistId(caseHandlePersonInfoDto.getHandlePersonId());
                    caseMainInfo.setHandlePersonAssistName(caseHandlePersonInfoDto.getHandlePersonName());
                }
            }
        }


        //2、组装宽表数据
        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        BeanUtils.copyProperties(saveDto, caseMainDetailInfo);
        caseMainDetailInfo.setCaseHappenTime(BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime()));
        String caseReason = "";
        if (!ObjectUtils.isEmpty(saveDto.getCaseReasonInfoList())) {
            for (CaseReasonInfoDto caseReasonInfoDto : saveDto.getCaseReasonInfoList()) {
                if (StringUtils.isEmpty(caseReason)) {
                    caseReason = BaseUtil.handleCaseReason(caseReasonInfoDto.getCaseReasonName());
                } else {
                    caseReason = caseReason + "，" + BaseUtil.handleCaseReason(caseReasonInfoDto.getCaseReasonName());
                }
            }
        }
        caseMainDetailInfo.setCaseReason(caseReason);
        caseMainDetailInfo.setUpdateTime(nowDate);
        caseMainDetailInfo.setCaseSourceId(saveDto.getCaseSourceId());
        caseMainDetailInfo.setCaseSourceReplenishId(saveDto.getCaseSourceReplenishId());
        caseMainDetailInfo.setCaseHappenAddressDetail(saveDto.getCaseHappenAddress());
        // 宽表中保存人设的案由
        if (!ObjectUtils.isEmpty(saveDto.getPersonReasonIds())) {
            caseMainDetailInfo.setPersonReasonId(JSON.toJSONString(saveDto.getPersonReasonIds()));
            caseMainDetailInfo.setPersonReasonName(saveDto.getPersonReasonNames().stream().collect(Collectors.joining(",")));
            // 多案由展示
            int size = saveDto.getPersonReasonNames().size();
            if (size > Constant.INTEGER_2) {
                saveDto.setPersonReasonName(saveDto.getPersonReasonNames().get(0) + "等" + size + "项");
            } else {
                saveDto.setPersonReasonName(saveDto.getPersonReasonNames().get(0));
            }
        }
        //增加应急案由数据处理
        if (!ObjectUtils.isEmpty(saveDto.getCaseEmergencyReasonList())) {
            List<CaseEmergencyReasonInfoDto> caseEmergencyReasonList = saveDto.getCaseEmergencyReasonList();
            caseMainDetailInfo.setCaseEmergencyReasonContent(JSON.toJSONString(caseEmergencyReasonList));
            //应急案由处理
            String caseEmergencyReasonName = caseEmergencyReasonList.get(0).getEmergencyReasonName();
            if (caseEmergencyReasonList.size() > 1) {
                caseEmergencyReasonName += "等";
            }
            saveDto.setCaseEmergencyReasonName(caseEmergencyReasonName);
        }
        if (!ObjectUtils.isEmpty(caseMainDetailInfo.getCaseHappenTime())) {
            saveDto.setCaseHappenTimeStr(DateTimeFormatter.ofPattern("yyyy年M月d日").format(caseMainDetailInfo.getCaseHappenTime()));
        }
        String uuid = BaseUtil.createUid();
        CaseMainInfo oldCaseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        if (ObjectUtil.isEmpty(saveDto.getCaseId())) {
            if (StringUtils.isNotEmpty(saveDto.getCaseSourceRegisterId())) {
                oldCaseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseSourceRegisterId());
                if (ObjectUtil.isNotEmpty(oldCaseMainInfo)) {
                    throw new BusinessException("案源已经转立案登记，请勿重复操作");
                }
                uuid = saveDto.getCaseSourceRegisterId();
                caseMainInfo.setDataSource(ApiVisitDataSourceEnum.PUNISH_AY.getCode());
                //查询案源信息
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(uuid);
                caseMainInfo.setCaseExternalActsCode(caseSourceRegisterMainInfo.getCaseSourceAppActsCode());
                //保存案源立案日志
                //CaseSourceRegisterMainInfo caseSourceRegisterMainInfo= caseSourceRegisterMainInfoMapper.selectByPrimaryKey(saveDto.getCaseSourceRegisterId());
                //saveCaseSourceRegisterFlow(caseSourceRegisterMainInfo);
            }
            caseMainInfo.setId(uuid);
            caseMainInfo.setCaseCreateTime(nowDate);
            caseMainInfoMapper.insertSelective(caseMainInfo);
            //新增宽表
            caseMainDetailInfo.setCreateTime(nowDate);
            caseMainDetailInfo.setId(BaseUtil.createUid());
            caseMainDetailInfo.setCaseId(uuid);
            caseMainDetailInfoMapper.insertSelective(caseMainDetailInfo);
            //将caseId放入saveDto
            saveDto.setCaseId(caseMainInfo.getId());
        } else {
            if (ObjectUtil.isEmpty(oldCaseMainInfo.getCaseCreateTime())) {
                caseMainInfo.setCaseCreateTime(nowDate);
            }
            //更新主表数据
            caseMainInfo.setId(saveDto.getCaseId());
            caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);
            //更新宽表数据
            CaseMainDetailInfo oldDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
            caseMainDetailInfo.setCaseId(caseMainInfo.getId());
            caseMainDetailInfo.setId(oldDetailInfo.getId());
            caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
        }
        Map<String, Object> rollMap = new HashMap<>();
        rollMap.put("workId", caseMainInfo.getId());
        rollMap.put("workFlowCode", workFlowCode);
        rollMap.put("stepSignal", "STEP-START");
        return rollMap;

    }

    /**
     * 案源立案流转日志保存
     *
     * @param caseSourceRegisterMainInfo
     * @return
     * @author liyafeng
     * @date 2022/8/18
     */
    private void saveCaseSourceRegisterFlow(CaseSourceRegisterMainInfo caseSourceRegisterMainInfo) {
        FlowCommonDto flowCommonDto = new FlowCommonDto();
        UserDTO userDTO = UserUtil.getUserInfo();
        flowCommonDto.setCaseSourceId(caseSourceRegisterMainInfo.getId());
        flowCommonDto.setStartPersonName(userDTO.getRealName());
        flowCommonDto.setStartPersonOrgName(userDTO.getOrgName());
        flowCommonDto.setFlowStartTime(new Date());
        flowCommonDto.setFlowEndTime(new Date());
        flowCommonDto.setStartPersonDeptName(userDTO.getDeptName());
        flowCommonDto.setFlowStageType(Constant.CASE_SOURCE_STAGE_LASP);
        caseSourceFlowRecordService.saveCommonFlowRecord(flowCommonDto);
    }

    /**
     * 描述：2、处理案件登记，保存案由信息
     *
     * @author shishengyao
     * @date 2022/05/18
     */
    private void dealCaseRegisterCaseReasonInfo(List<CaseReasonInfoDto> caseReasonInfoDtoList, String caseId, List<CaseReasonMainRecord> caseReasonMainRecords) {

        //之前老数据更新为失效
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        List<CaseReasonMainRecord> recordList = caseReasonMainRecordMapper.selectByExample(example);
        if (recordList != null && recordList.size() > 0) {
            for (CaseReasonMainRecord record : recordList) {
                record.setStatus(Constant.STRING_0);
                caseReasonMainRecordMapper.updateByPrimaryKey(record);
            }
        }
        if (ObjectUtil.isNotEmpty(caseReasonInfoDtoList) && caseReasonInfoDtoList.size() > 0) {
            for (CaseReasonInfoDto caseReasonInfoDto : caseReasonInfoDtoList) {
                CaseReasonMainRecord caseReasonMainRecord = new CaseReasonMainRecord();
                BeanUtils.copyProperties(caseReasonInfoDto, caseReasonMainRecord);
                caseReasonMainRecord.setCreateTime(LocalDateTime.now());
                caseReasonMainRecord.setId(BaseUtil.createUid());
                caseReasonMainRecord.setCaseId(caseId);
                caseReasonMainRecord.setCaseReasonNameSimple(BaseUtil.handleCaseReason(caseReasonInfoDto.getCaseReasonName()));
                caseReasonMainRecord.setIllegalBasisFormat(BaseUtil.removeHtml(caseReasonInfoDto.getIllegalBasis()));
                caseReasonMainRecord.setIllegalDetailFormat(BaseUtil.removeHtml(caseReasonInfoDto.getIllegalDetail()));
                caseReasonMainRecord.setPunishBasisFormat(BaseUtil.removeHtml(caseReasonInfoDto.getPunishBasis()));
                caseReasonMainRecord.setPunishDetailFormat(BaseUtil.removeHtml(caseReasonInfoDto.getPunishDetail()));
                caseReasonMainRecord.setStatus(Constant.STRING_1);
                String nodeIds = "";
                for (String str : caseReasonInfoDto.getCaseReasonIds()) {
                    if (StringUtils.isEmpty(nodeIds)) {
                        nodeIds = str;
                    } else {
                        nodeIds = nodeIds + "," + str;
                    }
                }
                caseReasonMainRecord.setCaseReasonNodeid(nodeIds);
                caseReasonMainRecords.add(caseReasonMainRecord);
                caseReasonMainRecordMapper.insertSelective(caseReasonMainRecord);
            }
        }
    }

    /**
     * 描述：3、处理案件登记，办案人员信息
     *
     * @author shishengyao
     * @date 2022/05/18
     */
    private void dealCaseRegisterHandlePersonInfo(List<CaseHandlePersonInfoDto> caseHandlePersonInfoDtoList, String caseId, UserDTO userInfo) {
        // 校验办案人员信息
        List<CaseHandlePersonInfoDto> mainHandlePersonList = caseHandlePersonInfoDtoList.stream().filter(e -> Constant.STRING_1.equals(e.getHandlePersonType())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(mainHandlePersonList) || mainHandlePersonList.size() < 1) {
            throw new BusinessException("主办人员不能为空");
        } else if (mainHandlePersonList.size() > 1) {
            throw new BusinessException("主办人员不能大于一个");
        }
        List<CaseHandlePersonInfoDto> assistHandlePersonList = caseHandlePersonInfoDtoList.stream().filter(e -> Constant.STRING_2.equals(e.getHandlePersonType())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(assistHandlePersonList) || assistHandlePersonList.size() < 1) {
            throw new BusinessException("协办人员不能为空");
        }
        List<String> repeatHandlePersonList = caseHandlePersonInfoDtoList.stream().map(CaseHandlePersonInfoDto::getHandlePersonId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isEmpty(repeatHandlePersonList) || repeatHandlePersonList.size() < caseHandlePersonInfoDtoList.size()) {
            throw new BusinessException("主办人员和协办人员不能重复");
        }

        //删除之前的办案人员
        Example example = new Example(CaseHandlePersonRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        caseHandlePersonRecordMapper.deleteByExample(example);
        for (CaseHandlePersonInfoDto handlePersonInfoDto : caseHandlePersonInfoDtoList) {
            CaseHandlePersonRecord caseHandlePersonRecord = new CaseHandlePersonRecord();
            BeanUtils.copyProperties(handlePersonInfoDto, caseHandlePersonRecord);
            caseHandlePersonRecord.setHandlePersonType(handlePersonInfoDto.getHandlePersonType());
            caseHandlePersonRecord.setDingId(handlePersonInfoDto.getDingId());
            if (ObjectUtil.isNotEmpty(handlePersonInfoDto.getHandlePersonId())) {
                String lawEnforcementCert = xzzfInterfaceService.getLawEnforcementCertWithUserId(handlePersonInfoDto.getHandlePersonId());
                if (ObjectUtil.isEmpty(lawEnforcementCert)) {
                    throw new BusinessException("办案人员" + handlePersonInfoDto.getHandlePersonName() + "的执法证为空!");
                }
                caseHandlePersonRecord.setLawEnforcementCert(lawEnforcementCert);
                handlePersonInfoDto.setLawEnforcementCert(lawEnforcementCert);
            }
            //  签名校验
            String handlePersonSignPic = null;
            try {
                handlePersonSignPic = commonService.getHandleSignData(handlePersonInfoDto.getHandlePersonId());
            } catch (Exception e) {
                e.printStackTrace();
                if ("true".equals(isCheckHandleSign)) {
                    if (ObjectUtil.isEmpty(handlePersonSignPic)) {
                        throw new BusinessException("因未获取承办人员" + handlePersonInfoDto.getHandlePersonName() + "有效签名信息，无法提交");
                    }
                }
            }
            caseHandlePersonRecord.setHandleSignPic(handlePersonSignPic);
            caseHandlePersonRecord.setId(BaseUtil.createUid());
            caseHandlePersonRecord.setCaseId(caseId);
            caseHandlePersonRecord.setHandleOrgCode(userInfo.getOrgCode());
            caseHandlePersonRecord.setHandleOrgName(userInfo.getOrgName());
            caseHandlePersonRecord.setHandleOrgTel(userInfo.getTelPhone());
            caseHandlePersonRecord.setHandleDeptCode(userInfo.getDeptCode());
            caseHandlePersonRecord.setHandleDeptName(userInfo.getDeptName());
            caseHandlePersonRecord.setHandleDeptTel(userInfo.getTelPhone());
            caseHandlePersonRecord.setHandlePersonTel(handlePersonInfoDto.getHandlePersonTel());
            caseHandlePersonRecord.setStatus(Constant.STRING_1);
            caseHandlePersonRecord.setAddTime(new Date());
            caseHandlePersonRecordMapper.insertSelective(caseHandlePersonRecord);
        }

    }

    /**
     * 描述：4、处理案件登记，保存当事人信息
     *
     * @author shishengyao
     * @date 2022/05/18
     */
    @WorkFlowRollAnnotation
    public Map<String, Object> dealCaseRegisterPartiesInfo(CaseRegisterSaveDto saveDto, String workFlowCode, List<CasePartiesRecord> partiesRecords) {
        String caseId = saveDto.getCaseId();
        //删除之前的当事人信息
        CasePartiesRecordSingleQueryDto queryDto = new CasePartiesRecordSingleQueryDto();
        queryDto.setCaseId(caseId);
        List<String> partyIds = new ArrayList<>();
        boolean flag = casePartiesRecordService.delCasePartiesRecordByCaseId(saveDto.getCaseId());
        Map<String, Object> rollMap = new HashMap<>();
        LocalDateTime createTime = LocalDateTime.now();
        if (flag) {
            List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoList = new ArrayList<>();
            // 法人当事人
            for (CaseRegisterPartiesLegalInfoDto legalInfoDto : saveDto.getPartiesLegalInfoList()) {
                //如果是人社条线，并且法定代表人身份证号是空的，根据单位名称，去请求接口获取法定代表人身份证号
                if (StrUtil.isNotEmpty(saveDto.getLineCode()) && saveDto.getLineCode().startsWith(TerritoryCodeEnum.RLSB.getCode()) && StrUtil.isEmpty(legalInfoDto.getLegalCertNo())) {
                    EntBaseInfoDto dto = new EntBaseInfoDto();
                    dto.setFrmc(legalInfoDto.getEntName());
                    dto.setTyxydm("");
                    EntBaseInfoVo vo = externalService.getEntBaseInfo(dto);
                    if (vo != null && StrUtil.isNotEmpty(vo.getFrZjhm())) {
                        legalInfoDto.setLegalCertNo(vo.getFrZjhm());
                    }
                }
                String partyIdUuid = BaseUtil.createUid();
                legalInfoDto.setId(partyIdUuid);
                CasePartiesLegalInfoDto casePartiesLegalInfo = new CasePartiesLegalInfoDto();
                BeanUtils.copyProperties(legalInfoDto, casePartiesLegalInfo);
                casePartiesLegalInfo.setAddress(legalInfoDto.getUnitAddress());
                casePartiesLegalInfo.setLegalName(legalInfoDto.getLegal());
                casePartiesLegalInfo.setCaseId(caseId);
                if (StrUtil.isNotEmpty(saveDto.getLineCode()) &&
                        saveDto.getLineCode().startsWith(TerritoryCodeEnum.STHJ.getCode())) {
                    casePartiesLegalInfo.setIsAffiliationCompany(legalInfoDto.getIsAffiliationCompany());
                    casePartiesLegalInfo.setIsListedCompany(legalInfoDto.getIsListedCompany());
                    casePartiesLegalInfo.setLegalContacts(legalInfoDto.getLegalContacts());
                    casePartiesLegalInfo.setEnterpriseType(legalInfoDto.getEnterpriseType());
                }
                casePartiesLegalInfo.setLegalIndustryType(legalInfoDto.getLegalIndustryType());
                casePartiesLegalInfo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
                casePartiesLegalInfoService.saveCasePartiesLegalInfo(casePartiesLegalInfo);

                //添加当事人表
                CasePartiesRecordDto casePartiesRecordDto = new CasePartiesRecordDto();
                casePartiesRecordDto.setCaseId(saveDto.getCaseId());
                casePartiesRecordDto.setId(BaseUtil.createUid());
                casePartiesRecordDto.setPartyId(partyIdUuid);
                casePartiesRecordDto.setPartyIdentityCode(legalInfoDto.getUniscid());
                casePartiesRecordDto.setPartyIdentityType(null);
                casePartiesRecordDto.setPartyName(legalInfoDto.getEntName());
                casePartiesRecordDto.setPartyType(PartyTypeEnum.LEGAL.getCode());
                createTime = createTime.plusSeconds(1L);
                casePartiesRecordDto.setCreateTime(createTime);
                casePartiesRecordService.saveCasePartiesInfo(casePartiesRecordDto);

                CasePartiesRecord partiesRecord = new CasePartiesRecord();
                BeanUtils.copyProperties(casePartiesRecordDto, partiesRecord);
                partiesRecords.add(partiesRecord);
                partyIds.add(partyIdUuid);
                //处理partyId
                legalInfoDto.setPartyId(partyIdUuid);
                partiesLegalInfoList.add(legalInfoDto);
            }
            List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoDtoList = new ArrayList<>();
            for (CaseRegisterPartiesPersonInfoDto personInfoDto : saveDto.getPartiesPersonInfoList()) {
                String partyIdUuid = BaseUtil.createUid();
                personInfoDto.setId(partyIdUuid);

                CasePartiesPersonInfoDto casePartiesPersonInfo = new CasePartiesPersonInfoDto();
                BeanUtils.copyProperties(personInfoDto, casePartiesPersonInfo);
                casePartiesPersonInfo.setCaseId(caseId);
                casePartiesPersonInfo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
                String[] addressAreas = personInfoDto.getAddressAreas();
                if (ArrayUtil.isNotEmpty(addressAreas)) {
                    casePartiesPersonInfo.setAddressAreasStr(String.join(",", addressAreas));
                }
                casePartiesPersonInfoService.saveCasePartiesPersonInfo(casePartiesPersonInfo);
                //添加当事人表
                CasePartiesRecordDto casePartiesRecordDto = new CasePartiesRecordDto();
                casePartiesRecordDto.setCaseId(saveDto.getCaseId());
                casePartiesRecordDto.setId(BaseUtil.createUid());
                casePartiesRecordDto.setPartyId(partyIdUuid);
                casePartiesRecordDto.setPartyIdentityCode(personInfoDto.getCertNo());
                casePartiesRecordDto.setPartyIdentityType(personInfoDto.getCertType());
                casePartiesRecordDto.setPartyName(personInfoDto.getName());
                casePartiesRecordDto.setPartyType(PartyTypeEnum.PERSON.getCode());
                createTime = createTime.plusSeconds(1L);
                casePartiesRecordDto.setCreateTime(createTime);
                casePartiesRecordDto.setAddressDetail(personInfoDto.getAddressDetail());
                casePartiesRecordDto.setAddressAreas(String.join(",", personInfoDto.getAddressAreas()));
                casePartiesRecordService.saveCasePartiesInfo(casePartiesRecordDto);
                CasePartiesRecord partiesRecord = new CasePartiesRecord();
                BeanUtils.copyProperties(casePartiesRecordDto, partiesRecord);
                partiesRecords.add(partiesRecord);
                partyIds.add(partyIdUuid);
                //处理partyId
                personInfoDto.setPartyId(partyIdUuid);
                partiesPersonInfoDtoList.add(personInfoDto);
            }
            saveDto.setPartyIds(partyIds.stream().collect(Collectors.joining(",")));
            saveDto.setPartiesLegalInfoList(partiesLegalInfoList);
            saveDto.setPartiesPersonInfoList(partiesPersonInfoDtoList);

            rollMap.put("workId", saveDto.getCaseId());
            rollMap.put("workSubId", saveDto.getPartyIds());
            rollMap.put("workFlowCode", workFlowCode);
            rollMap.put("stepSignal", "STEP-START");
        }
        return rollMap;
    }

    /**
     * 描述：5、处理案件登记，保存附件信息
     *
     * @author shishengyao
     * @date 2022/05/18
     */
    private void dealCaseRegisterAppendixInfo(CaseRegisterSaveDto saveDto, String documentCatalogCode) {
//        List<String> punishIds = saveDto.getCaseReasonInfoList().stream().map(CaseReasonInfoDto::getCaseReasonCode).collect(Collectors.toList());
        //获取立案材料配置信息
//        configRegisterCaseFileService.getFileListByRelId(punishIds);
        //删除之前的附件
        Example example = new Example(CaseAppendixRecord.class);
        example.createCriteria().andEqualTo("caseId", saveDto.getCaseId()).andEqualTo("documentCatalogCode", documentCatalogCode);
        caseAppendixRecordMapper.deleteByExample(example);
        if (!ObjectUtils.isEmpty(saveDto.getAppendixList())) {
            List<AppendixDto> appendixList = saveDto.getAppendixList();
            for (AppendixDto appendixDto : appendixList) {
                CaseAppendixRecord record = new CaseAppendixRecord();
                record.setCaseId(saveDto.getCaseId());
                record.setCaseStageName(CaseStageEnum.CASE_REGISTER.getDes());
                record.setCaseStageCode(CaseStageEnum.CASE_REGISTER.getCode());
                record.setAppendixUrl(appendixDto.getAppendixUrl());
                record.setAppendixTypeId(appendixDto.getAppendixTypeId());
                record.setAppendixName(appendixDto.getAppendixName());
                record.setIsMaterial(appendixDto.getIsMaterial());
                record.setDocumentCatalogCode(documentCatalogCode);
                record.setId(BaseUtil.createUid());
                // 检查证据
                record.setIsEvidenceCenter(appendixDto.getIsEvidenceCenter());
                record.setEvidenceUid(appendixDto.getEvidenceUid());
                record.setEvidenceLinkType(appendixDto.getEvidenceLinkType());
                caseAppendixRecordService.saveCaseAppendixRecord(record);
            }
        }

    }

    /**
     * 描述：处理案件详情补充表
     *
     * @author shishengyao
     * @date 2022/05/18
     */
    private void dealCaseRegisterAuxiliaryInfo(CaseRegisterSaveDto saveDto, List<CaseReasonMainRecord> caseReasonMainRecords, List<CasePartiesRecord> partiesRecords) {
        Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
        example.createCriteria().andEqualTo("caseId", saveDto.getCaseId());
        caseMainDetailAuxiliaryInfoMapper.deleteByExample(example);
        CaseMainDetailAuxiliaryInfo auxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
        auxiliaryInfo.setCaseId(saveDto.getCaseId());
        //多案由单当事人
        if (PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode().equals(saveDto.getCasePartiesReasonType())) {
            for (CaseReasonMainRecord reasonMainRecord : caseReasonMainRecords) {
                auxiliaryInfo.setId(BaseUtil.createUid());
                auxiliaryInfo.setCaseReasonId(reasonMainRecord.getId());
                auxiliaryInfo.setCaseReasonName(reasonMainRecord.getCaseReasonName());
                auxiliaryInfo.setPartyId(partiesRecords.get(0).getPartyId());
                auxiliaryInfo.setPartyName(partiesRecords.get(0).getPartyName());
                caseMainDetailAuxiliaryInfoMapper.insertSelective(auxiliaryInfo);
            }
        }
        //多当事人单案由
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(saveDto.getCasePartiesReasonType())) {
            for (CasePartiesRecord partiesRecord : partiesRecords) {
                auxiliaryInfo.setId(BaseUtil.createUid());
                if (!ObjectUtils.isEmpty(caseReasonMainRecords)) {
                    auxiliaryInfo.setCaseReasonId(caseReasonMainRecords.get(0).getId());
                    auxiliaryInfo.setCaseReasonName(caseReasonMainRecords.get(0).getCaseReasonName());
                } else {
                    auxiliaryInfo.setCaseReasonId("");
                    auxiliaryInfo.setCaseReasonName("");
                }
                auxiliaryInfo.setPartyId(partiesRecord.getPartyId());
                auxiliaryInfo.setPartyName(partiesRecord.getPartyName());
                caseMainDetailAuxiliaryInfoMapper.insertSelective(auxiliaryInfo);
            }

        }
        //单案由单当事人
        if (PartiesReasonTypeEnum.SINGLE_PARTY.getCode().equals(saveDto.getCasePartiesReasonType())) {
            auxiliaryInfo.setId(BaseUtil.createUid());
            if (!ObjectUtils.isEmpty(caseReasonMainRecords)) {
                auxiliaryInfo.setCaseReasonId(caseReasonMainRecords.get(0).getId());
                auxiliaryInfo.setCaseReasonName(caseReasonMainRecords.get(0).getCaseReasonName());
            }
            if (!ObjectUtils.isEmpty(partiesRecords)) {
                auxiliaryInfo.setPartyId(partiesRecords.get(0).getPartyId());
                auxiliaryInfo.setPartyName(partiesRecords.get(0).getPartyName());
            }
            caseMainDetailAuxiliaryInfoMapper.insertSelective(auxiliaryInfo);
            /*for (CasePartiesRecord partiesRecord : partiesRecords) {
                auxiliaryInfo.setId(BaseUtil.createUid());
                if (!ObjectUtils.isEmpty(caseReasonMainRecords)) {
                    auxiliaryInfo.setCaseReasonId(caseReasonMainRecords.get(0).getId());
                    auxiliaryInfo.setCaseReasonName(caseReasonMainRecords.get(0).getCaseReasonName());
                } else {
                    auxiliaryInfo.setCaseReasonId("");
                    auxiliaryInfo.setCaseReasonName("");
                }
                auxiliaryInfo.setPartyId(partiesRecord.getPartyId());
                auxiliaryInfo.setPartyName(partiesRecord.getPartyName());
                caseMainDetailAuxiliaryInfoMapper.insertSelective(auxiliaryInfo);
            }*/

        }

    }


    /**
     * 描述：处理关联文书
     *
     * @param saveDto 保存dto
     * @author shishengyao
     * @date 2022/06/17
     */
    private void dealCaseRegisterRelatedDocumentInfo(CaseRegisterSaveDto saveDto) {

        // 删除原有的关联文书
        caseRelatedDocumentRecordService.deleteCaseRelatedDocumentByCaseId(saveDto.getCaseId());
        if (ObjectUtil.isNotEmpty(saveDto.getRelatedDocumentList())) {
            //保存关联文书
            CaseRelatedDocumentSaveDto relatedDocumentSaveDto = new CaseRelatedDocumentSaveDto();
            relatedDocumentSaveDto.setCaseId(saveDto.getCaseId());
            relatedDocumentSaveDto.setRelatedDocumentList(saveDto.getRelatedDocumentList());
            caseRelatedDocumentRecordService.saveCaseRelatedDocument(relatedDocumentSaveDto);
        }
    }

    /**
     * 描述：暂存
     *
     * @param saveDto 保存dto
     * @return {@link CaseMainInfo }
     * @author shishengyao
     * @date 2022/05/23
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveCaseRegisterTemporary(CaseRegisterSaveDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        //       SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(userInfo.getOrgCode());
//        if (ObjectUtil.isEmpty(saveDto.getOrgStandardName())){
//            if (ObjectUtil.isEmpty(sysDepartParam.getOrgStandardName())){
//                throw new BusinessException("办案单位暂未维护文书抬头");
//            }else {
//                saveDto.setOrgStandardName(sysDepartParam.getOrgStandardName());
//            }
//        }
//        if (TransferCaseSourceEnum.CASE_SOURCE_YGBMYS.getCfCode().equals(saveDto.getCaseSourceId())){
//          if(ObjectUtil.isEmpty(saveDto.getTransferUnitUniscid())){
//              throw new BusinessException("未匹配到移送单位"+saveDto.getTransferUnit()+"统一社会信用代码信息，请联系管理员");
//            }
//        }
        //获取办案条线对应的领域
        LineDTO lineDTO = xzzfInterfaceService.getLineInfoByLineCode(saveDto.getLineCode());
        saveDto.setCaseTerritoryCode(lineDTO.getTerritoryCode());
        saveDto.setCaseTerritoryName(lineDTO.getTerritoryName());
        //1、获取领域下业务参数
        //获取流程信息--调用公用接口
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        //修改为选择的条线领域
        request.setApplyFieldCode(saveDto.getCaseTerritoryCode());
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        //业务参数Id
        String busiParamId = configBusiParamMainList.get(0).getId();
        ConfigBusiParamDocumentInfo paramDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, DocumentKindEnum.DOC_KIND_LASPB.getCode());
        String caseId = saveDto.getCaseId();

        //1.添加案件主表
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        boolean flag = false;
        if (caseMainInfo == null) {
            caseMainInfo = new CaseMainInfo();
            //检查转处罚设置caseId与检查业务id一致
            if (ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(saveDto.getCaseSourceAppId())) {
                caseMainInfo.setId(saveDto.getCaseSourceRegisterId());
            } else {
                caseMainInfo.setId(BaseUtil.createUid());
            }
            saveDto.setCaseId(caseMainInfo.getId());
            caseId = caseMainInfo.getId();
            flag = true;
        }
        caseMainInfo.setLineName(saveDto.getLineName());
        caseMainInfo.setLineCode(saveDto.getLineCode());
        caseMainInfo.setBusiParamId(busiParamId);
        caseMainInfo.setCaseName(saveDto.getCaseName());
        //设置案件类型--普通程序
        //caseMainInfo.setCaseType(CaseTypeEnum.NORMAL_PROCEDURE.getCode());
        caseMainInfo.setCaseType(saveDto.getCaseType());
        caseMainInfo.setCaseSource(saveDto.getCaseSource());
        //暂存
        caseMainInfo.setCaseStatus(CaseStatusEnum.TEMP.getCode());
        caseMainInfo.setCaseOrgCode(userInfo.getOrgCode());
        caseMainInfo.setCaseOrgName(userInfo.getOrgName());
        caseMainInfo.setCaseDeptCode(userInfo.getDeptCode());
        caseMainInfo.setCaseDeptName(userInfo.getDeptName());
        caseMainInfo.setCaseCurrentStageName("暂存");

        //案源转处罚增加案源id及数据来源
        caseMainInfo.setDataSourceServiceId(saveDto.getCaseSourceRegisterId());
        caseMainInfo.setDataSource(saveDto.getCaseSourceAppId());

        //保存外部行政行为码
        caseMainInfo.setCaseExternalActsCode(saveDto.getCaseExternalActsCode());
        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        //BeanUtils.copyProperties(caseMainInfo, caseMainDetailInfo);
        BeanUtils.copyProperties(saveDto, caseMainDetailInfo);
        caseMainDetailInfo.setCaseHappenTime(BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime()));
        caseMainDetailInfo.setCaseSourceId(saveDto.getCaseSourceId());
        // 宽表中保存人设的案由
        if (!ObjectUtils.isEmpty(saveDto.getPersonReasonIds())) {
            caseMainDetailInfo.setPersonReasonId(JSON.toJSONString(saveDto.getPersonReasonIds()));
            caseMainDetailInfo.setPersonReasonName(saveDto.getPersonReasonNames().stream().collect(Collectors.joining(",")));
        }
        if (flag) {
            caseMainInfoMapper.insertSelective(caseMainInfo);
            //新增宽表
            caseMainDetailInfo.setCreateTime(LocalDateTime.now());
            caseMainDetailInfo.setId(BaseUtil.createUid());
            caseMainDetailInfo.setCaseId(caseMainInfo.getId());
            caseMainDetailInfoMapper.insertSelective(caseMainDetailInfo);
        } else {
            caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);
            //更新宽表数据
            CaseMainDetailInfo oldDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
            caseMainDetailInfo.setCaseId(caseMainInfo.getId());
            caseMainDetailInfo.setId(oldDetailInfo.getId());
            caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
        }
        if (ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(saveDto.getCaseSourceAppId())) {
            //处理办案人员
            dealCaseRegisterHandlePersonInfoOfCheck(saveDto.getHandlePersonInfoList(), caseId, userInfo);
        } else {
            //处理办案人员
            dealCaseRegisterHandlePersonInfo(saveDto.getHandlePersonInfoList(), caseId, userInfo);
        }
        //处理当事人信息
        List<CasePartiesRecord> partiesRecords = new ArrayList();
        try {
            dealCaseRegisterPartiesInfo(saveDto, "", partiesRecords);
        } catch (Exception exception) {
            //非检查转普通程序抛出异常
            if (!ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(saveDto.getCaseSourceAppId())) {
                throw new BusinessException(exception.getMessage());
            }
        }
        //案由
        List<CaseReasonMainRecord> caseReasonMainRecords = new ArrayList<>();
        // 非人社还走以前流程。
        if (!Constant.HUMAN_SOCIETY_BARS_CODE.equals(saveDto.getLineCode().substring(0, 4))) {
            dealCaseRegisterCaseReasonInfo(saveDto.getCaseReasonInfoList(), caseId, caseReasonMainRecords);
        }
        //查询并更新文书记录表的文书内容
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, paramDocumentInfo.getDocumentCatalogCode());
        if (ObjectUtil.isNotEmpty(caseDocumentRecord)) {
            Example updateE = new Example(CaseDocumentRecord.class);
            updateE.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("documentCatalogCode", caseDocumentRecord.getDocumentCatalogCode());
            CaseDocumentRecord newCaseDocumentRecord = new CaseDocumentRecord();
            newCaseDocumentRecord.setDocumentContent(JSONObject.toJSONString(saveDto));
            //设置文书为草稿状态
            newCaseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.DRAFT.getCode());
            caseDocumentRecordMapper.updateByExampleSelective(newCaseDocumentRecord, updateE);
        }

        //删除原暂存表数据并添加到暂存表
        caseTemporaryRecordService.removeTemporary(saveDto.getCaseId(), paramDocumentInfo.getDocumentCatalogCode());
        CaseTemporaryRecord record = new CaseTemporaryRecord();
        record.setId(BaseUtil.createUid());
        record.setCaseId(saveDto.getCaseId());
        record.setContent(JSONObject.toJSONString(saveDto));
        record.setAddUser(userInfo.getLoginName());
        record.setCreateTime(LocalDateTime.now());
        record.setDocumentCatalogCode(paramDocumentInfo.getDocumentCatalogCode());
        return caseTemporaryRecordMapper.insertSelective(record);
    }

    @Override
    public CaseRegisterInfoVo getCaseRegisterInfo(CaseRegisterDetailQueryDto queryDto) {
        CaseDocumentRecordDto recordDto = caseDocumentRecordService.getCaseDocumentRecordByKindCode(queryDto.getCaseId(), "LASPB");
        String content = "";
        String caseId = queryDto.getCaseId();
        if (recordDto == null) {
            String kindCode = DocumentKindEnum.DOC_KIND_LASPB.getCode();
            String documentCatalogCode;
            List<ConfigBusiParamDocumentInfo> configList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId, null, kindCode);
            if (!ObjectUtils.isEmpty(configList)) {
                documentCatalogCode = configList.get(Constant.INTEGER_0).getDocumentCatalogCode();
            } else {
                throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",kindCode:" + kindCode);
            }
            //查询暂存表是否有数据
            Example example = new Example(CaseTemporaryRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("documentCatalogCode", documentCatalogCode);
            List<CaseTemporaryRecord> list = caseTemporaryRecordMapper.selectByExample(example);
            if (ObjectUtil.isNotEmpty(list) && list.size() > 0) {
                content = list.get(0).getContent();
            }
        } else {
            content = recordDto.getDocumentContent();
        }
        if (ObjectUtil.isNotEmpty(content)) {
            JSONObject jsonObj = JSONObject.parseObject(content);
            CaseRegisterInfoVo registerInfoVo = JSONObject.toJavaObject(jsonObj, CaseRegisterInfoVo.class);
            //特殊处理旧数据
            if (!jsonObj.containsKey("handlePersonInfoList")) {
                CaseRegisterInfoVo newRegisterInfoVo = new CaseRegisterInfoVo();
                BeanUtils.copyProperties(registerInfoVo, newRegisterInfoVo);
                List<CaseHandlePersonInfoDto> handlePersonInfoList = new ArrayList<>();
                List<CaseHandlePersonRecord> handlePersons = caseHandlePersonRecordService.getCaseHandlePersonRecordList(queryDto.getCaseId());
                for (CaseHandlePersonRecord personRecord : handlePersons) {
                    CaseHandlePersonInfoDto handlePersonInfoDto = new CaseHandlePersonInfoDto();
                    BeanUtils.copyProperties(personRecord, handlePersonInfoDto);
                    handlePersonInfoList.add(handlePersonInfoDto);
                }
                List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoList = new ArrayList<>();
                List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoList = new ArrayList<>();
                List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(queryDto.getCaseId());
                for (CasePartiesRecordVo partiesRecordVo : casePartiesInfo) {
                    if (PartyTypeEnum.PERSON.getCode().equals(partiesRecordVo.getPartyType())) {
                        CaseRegisterPartiesPersonInfoDto personInfoDto = new CaseRegisterPartiesPersonInfoDto();
                        CasePartiesPersonInfo personInfo = casePartiesPersonInfoMapper.selectByPrimaryKey(partiesRecordVo.getPartyId());
                        BeanUtils.copyProperties(personInfo, personInfoDto);
                        personInfoDto.setBirth(BaseUtil.getFormatDate(personInfo.getBirth()));
                        if (ObjectUtil.isNotEmpty(jsonObj.get("addressAreas"))) {
                            personInfoDto.setAddressAreas(JSONArray.parseArray(JSON.toJSONString(jsonObj.get("addressAreas"))).toJavaObject(String[].class));
                        }
                        personInfoDto.setAddressDetail(personInfo.getAddress());
                        partiesPersonInfoList.add(personInfoDto);
                    } else if (PartyTypeEnum.LEGAL.getCode().equals(partiesRecordVo.getPartyType())) {
                        CaseRegisterPartiesLegalInfoDto legalInfoDto = new CaseRegisterPartiesLegalInfoDto();
                        CasePartiesLegalInfo legalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(partiesRecordVo.getPartyId());
                        BeanUtils.copyProperties(legalInfo, legalInfoDto);
                        partiesLegalInfoList.add(legalInfoDto);
                    }

                }
                CaseReasonMainRecordQueryDto recordQueryDto = new CaseReasonMainRecordQueryDto();
                recordQueryDto.setCaseId(queryDto.getCaseId());
                recordQueryDto.setStatus("1");
                List<CaseReasonMainRecordVo> caseReasonInfos = caseReasonMainRecordMapper.selectCaseReasonRecordList(recordQueryDto);
                List<CaseReasonInfoDto> caseReasonInfoList = new ArrayList<>();

                for (CaseReasonMainRecordVo reasonMainRecordVo : caseReasonInfos) {
                    CaseReasonInfoDto caseReasonInfoDto = new CaseReasonInfoDto();
                    BeanUtils.copyProperties(reasonMainRecordVo, caseReasonInfoDto);
                    caseReasonInfoDto.setCaseReasonIds(reasonMainRecordVo.getCaseReasonNodeid().split(","));
                    caseReasonInfoList.add(caseReasonInfoDto);
                }
                // TODO 人设案由回显
                //newRegisterInfoVo.setPersonReasonIds("");
                newRegisterInfoVo.setCaseReasonInfoList(caseReasonInfoList);
                newRegisterInfoVo.setHandlePersonInfoList(handlePersonInfoList);
                newRegisterInfoVo.setPartiesLegalInfoList(partiesLegalInfoList);
                newRegisterInfoVo.setPartiesPersonInfoList(partiesPersonInfoList);
                newRegisterInfoVo.setCaseHappenAddress(jsonObj.getString("happenAddress"));
                newRegisterInfoVo.setCaseConciseCondition(jsonObj.getString("conciseCondition"));
                newRegisterInfoVo.setCaseHappenTime(jsonObj.getString("happenTime"));
                newRegisterInfoVo.setCaseHappenAddressDetail(jsonObj.getString("happenAddressDetail"));
                if (ObjectUtil.isNotEmpty(jsonObj.get("happenAddressAreas"))) {
                    newRegisterInfoVo.setCaseHappenAddressAreaNames(JSONArray.parseArray(JSON.toJSONString(jsonObj.get("happenAddressAreas"))).toJavaObject(String[].class));

                }
                registerInfoVo = newRegisterInfoVo;
            }
            CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            if (null != caseMainInfo) {
                registerInfoVo.setCaseType(caseMainInfo.getCaseType());
            }
            //如果是速结程序的话，则判断速结程序告知书是否已签字确认：没有也算没有签字
            if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(caseMainInfo.getCaseType())) {
                UserDTO userInfo = UserUtil.getUserInfo();
                String documentCatalogCodeOfSJGZS = null;
                try {
                    documentCatalogCodeOfSJGZS = caseDocumentRecordService.getDocumentCatalogCodeOfSJGZS(userInfo.getAreaCode(), caseMainInfo.getBusiParamId());
                } catch (Exception exception) {
                    documentCatalogCodeOfSJGZS = null;
                }
                //ConfigBusiParamDocumentInfo fastNoticeConfig = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK2SJCXGZS.getCode());
                if (documentCatalogCodeOfSJGZS != null) {
                    CaseDocumentRecord fastNoticeRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCodeOfSJGZS);
                    if (fastNoticeRecord != null && DocumentStatusEnum.CONFIRM_END.getCode().equals(fastNoticeRecord.getDocumentSignstampedStatus())) {
                        registerInfoVo.setFastNoticeIsSign(YesOrNoEnum.YES.getCode());
                    } else {
                        registerInfoVo.setFastNoticeIsSign(YesOrNoEnum.NO.getCode());
                    }
                }
            }
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
            //人社条线案由回显
            if (TerritoryCodeEnum.RLSB.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
                List<PersonReasonIds> list = registerInfoVo.getPersonReasonIds();
                for (int i = 0; i < list.size(); i++) {
                    PersonReasonIds personReasonIds = list.get(i);
                    if (StrUtil.isNotEmpty(personReasonIds.getCaseReasonName())) {
                        break;
                    } else {
                        String personReasonName = caseMainDetailInfo.getPersonReasonName();
                        if (StrUtil.isNotEmpty(personReasonName)) {
                            //案由名称
                            String[] reasonNameArr = personReasonName.split(Constant.STRING_COMMA);
                            personReasonIds.setCaseReasonName(reasonNameArr[i]);
                        }
                    }
                }
            }
            registerInfoVo.setIsIndustrialTradeSpecial(caseMainDetailInfo == null ? Constant.STRING_0 : caseMainDetailInfo.getIsIndustrialTradeSpecial());
            registerInfoVo.setSimpleFormType(caseMainDetailInfo.getSimpleFormType());
            return registerInfoVo;
        }
        return null;
    }

    @Override
    public List<RepeatCaseInfoVo> getRepeatCaseInfoList(RepeatCaseInfoPageRequest pageRequest) {
        UserDTO userInfo = UserUtil.getUserInfo();
        List<CasePartiesRecord> casePartiesRecordList = new ArrayList<>();
        List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoDtos = pageRequest.getPartiesLegalInfoList();
        if (pageRequest.getPartiesLegalInfoList().size() > 0) {
            for (CaseRegisterPartiesLegalInfoDto legalInfoDto : partiesLegalInfoDtos) {
                CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
                casePartiesRecord.setPartyIdentityCode(legalInfoDto.getUniscid());
                casePartiesRecord.setPartyName(legalInfoDto.getEntName());
                casePartiesRecordList.add(casePartiesRecord);
            }
        }
        List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoList = pageRequest.getPartiesPersonInfoList();
        if (pageRequest.getPartiesPersonInfoList().size() > 0) {
            for (CaseRegisterPartiesPersonInfoDto personInfoDto : partiesPersonInfoList) {
                CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
                casePartiesRecord.setPartyIdentityCode(personInfoDto.getCertNo());
                casePartiesRecord.setPartyIdentityType(personInfoDto.getCertType());
                casePartiesRecord.setPartyName(personInfoDto.getName());
                casePartiesRecordList.add(casePartiesRecord);
            }
        }
        pageRequest.setCasePartiesRecordList(casePartiesRecordList);
        Map<String, Object> map = new HashMap<>(4);
        if (!ObjectUtils.isEmpty(pageRequest.getCaseReasonInfoList())) {
            String caseReasonCodes = pageRequest.getCaseReasonInfoList().stream().map(e -> e.getCaseReasonCode()).collect(Collectors.joining(","));
            map.put("caseReasonCodes", caseReasonCodes);
        }
        map.put("happenTime", pageRequest.getCaseHappenTime());
        map.put("caseId", pageRequest.getCaseId());
        map.put("casePartiesRecordList", pageRequest.getCasePartiesRecordList());
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getLength(), pageRequest.getOrderBy());
        List<RepeatCaseInfoVo> caseList = caseMainDetailInfoMapper.selectRepeatCaseByReasonsAndHappenTime(map);
        if (caseList.size() > 0) {
            for (RepeatCaseInfoVo vo : caseList) {
                List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(vo.getCaseId());
                vo.setPartyShowName(vo.getPartyShowName());
                vo.setPartyFullName(vo.getPartyFullName());
                if (casePartiesRecords.size() > 1) {
                    vo.setPartyType("3");
                    String partiesName = casePartiesRecords.stream().map(e -> e.getPartyName()).collect(Collectors.joining(","));
                    vo.setPartyShowName(vo.getPartyShowName() + "等" + casePartiesRecords.size() + "个");
                    vo.setPartyFullName(partiesName);
                }
                if (StringUtils.isNotEmpty(vo.getPartyType()) && vo.getPartyType().equals(Constant.STRING_2)) {
                    CasePartiesLegalInfo legalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(vo.getPartyId());
                    vo.setCasePartiesLegalInfo(legalInfo);
                }
                //1.循环设置处理人员
                List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordService.getCaseHandlePersonRecordList(vo.getCaseId());
                for (CaseHandlePersonRecord caseHandlePersonRecord : handlePersonRecords) {
                    if (Constant.STRING_1.equals(caseHandlePersonRecord.getHandlePersonType())) {
                        vo.setMainHandlePerson(caseHandlePersonRecord.getHandlePersonName());
                    } else if (Constant.STRING_2.equals(caseHandlePersonRecord.getHandlePersonType())) {
                        vo.setAssistHandlePerson(caseHandlePersonRecord.getHandlePersonName());
                    }
                }
                List<CaseHandlePersonRecord> collect = handlePersonRecords.stream().filter(e -> e.getHandlePersonId().equals(userInfo.getUserId().toString())).collect(Collectors.toList());
                if (collect.size() > 0) {
                    vo.setIsOwnCase(Constant.STRING_1);
                }
                vo.setCaseTypeName(CaseTypeEnum.getValueByCode(vo.getCaseType()));
            }
        }
        return caseList;
    }


    /**
     * 描述： 根据案由编码及当事人获取N年内重复违法次数
     *
     * @return {@link int}
     * @author: zhengqiang
     * @date: 2022/7/20
     * @param: queryDto
     **/
    @Override
    public List<CaseMainReasonRepeatCountVo> getCaseRepeatCountByReasonAndParty(CaseRepeatRequest request) {
        List<CaseMainReasonRepeatCountVo> countList = new ArrayList<>();

        CaseRepeatQueryDto queryDto = new CaseRepeatQueryDto();
        //查询配置年数
        String year = "'" + repeatCaseParamOfYears + " year'";
        queryDto.setYear(year);
        //案由处理
        List<CaseReasonInfoDto> caseReasonInfoList = request.getCaseReasonInfoList();
        if (ObjectUtils.isEmpty(caseReasonInfoList)) {
            throw new BusinessException("案由列表不能为空");
        }
        List<String> caseReasonCodes = caseReasonInfoList.stream().map(e -> e.getCaseReasonCode()).filter(code -> code != null).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(caseReasonCodes)) {
            throw new BusinessException("案由编码不能为空");
        }
        queryDto.setCaseReasonCodes(caseReasonCodes);

        // 法人当事人
        if (!ObjectUtils.isEmpty(request.getPartiesLegalInfoList())) {
            for (CaseRegisterPartiesLegalInfoDto legalInfoDto : request.getPartiesLegalInfoList()) {
                //单位社会信用代码未传不返回记录
                if (ObjectUtils.isEmpty(legalInfoDto.getUniscid())) break;

                CaseMainReasonRepeatCountVo vo = new CaseMainReasonRepeatCountVo();
                vo.setPartyName(legalInfoDto.getEntName());
                vo.setPartyType(PartyTypeEnum.LEGAL.getCode());
                vo.setPartyIdentityCode(legalInfoDto.getUniscid());
                //查询违法次数
                queryDto.setPartyType(PartyTypeEnum.LEGAL.getCode());
                queryDto.setPartyIdentityCode(legalInfoDto.getUniscid());
                int count = caseMainInfoMapper.selectCaseRepeatCountByReasonAndParty(queryDto);
                //没有重复违法次数不返回记录
                if (count == 0) continue;

                vo.setCount("" + count);
                countList.add(vo);
            }
        }

        //个人
        if (!ObjectUtils.isEmpty(request.getPartiesPersonInfoList())) {
            for (CaseRegisterPartiesPersonInfoDto personInfoDto : request.getPartiesPersonInfoList()) {
                //个人身份证未传不返回记录
                if (ObjectUtils.isEmpty(personInfoDto.getCertNo())) break;

                if (ObjectUtils.isEmpty(personInfoDto.getCertType())) {
                    throw new BusinessException("当事人为个人，当事人证件类型不能为空");
                }
                CaseMainReasonRepeatCountVo vo = new CaseMainReasonRepeatCountVo();
                vo.setPartyName(personInfoDto.getName());
                vo.setPartyType(PartyTypeEnum.PERSON.getCode());
                vo.setPartyIdentityCode(personInfoDto.getCertNo());
                vo.setPartyIdentityType(personInfoDto.getCertType());

                //查询违法次数
                queryDto.setPartyType(PartyTypeEnum.PERSON.getCode());
                queryDto.setPartyIdentityCode(personInfoDto.getCertNo());
                queryDto.setPartyIdentityType(personInfoDto.getCertType());
                int count = caseMainInfoMapper.selectCaseRepeatCountByReasonAndParty(queryDto);
                //没有重复违法次数不返回记录
                if (count == 0) continue;

                vo.setCount("" + count);
                countList.add(vo);
            }
        }

        return countList;
    }

    /**
     * 【V1.3.2】描述： 根据案由编码及当事人获取N年内重复违法列表
     *
     * @return {@link List< CaseMainReasonRepeatVo>}
     * @author: zhengqiang
     * @date: 2022/7/21
     * @param: pageRequest
     **/
    @Override
    public List<CaseMainReasonRepeatVo> getCaseRepeatListByReasonAndParty(CaseMainReasonRepeatPageRequest pageRequest) {
        //查询配置年数
        String year = "'" + repeatCaseParamOfYears + " year'";
        pageRequest.setYear(year);

        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getLength(), pageRequest.getOrderBy());
        List<CaseMainReasonRepeatVo> caseMainReasonRepeatVos = caseMainInfoMapper.selectCaseRepeatListByReasonAndParty(pageRequest);
        caseMainReasonRepeatVos.forEach(vo -> {
            vo.setCaseTypeName(CaseTypeEnum.getValueByCode(vo.getCaseType()));
            //案由名称处理
            List<CaseReasonMainRecordVo> caseReasonMainRecordList = caseReasonMainRecordService.getCaseReasonRecordListByCaseId(vo.getCaseId());
            if (ObjectUtil.isNotEmpty(caseReasonMainRecordList) && caseReasonMainRecordList.size() > 0) {
                String reasonName = caseReasonMainRecordList.stream().map(e -> e.getCaseReasonName()).filter(name -> name != null).collect(Collectors.joining(","));
                vo.setCaseReasonName(reasonName);
            }
            //查询处罚决定书地址
            Example docRecord = new Example(CaseDocumentRecord.class);
            if (ObjectUtils.isEmpty(vo.getPunishDocumentNumber())) {
                return;
            }
            docRecord.createCriteria().andEqualTo("caseId", vo.getCaseId()).andEqualTo("documentNumber", vo.getPunishDocumentNumber());
            List<CaseDocumentRecord> documentRecords = caseDocumentRecordMapper.selectByExample(docRecord);
            if (!ObjectUtils.isEmpty(documentRecords)) {
                CaseDocumentRecord caseDocumentRecord = documentRecords.get(0);
                String docUrl = !ObjectUtils.isEmpty(caseDocumentRecord.getDocumentUrlAfterSign()) ? caseDocumentRecord.getDocumentUrlAfterSign() : caseDocumentRecord.getDocumentUrlAfterSeal();
                vo.setDocumentUrl(docUrl);
            }
        });
        return caseMainReasonRepeatVos;
    }

    /**
     * 描述： 根据名称搜索机构用户
     *
     * @return {@link Result}
     * @author: zhengqiang
     * @date: 2022/8/2
     * @param: userName
     **/
    @Override
    public List<HandleAssistVo> searchOrgUserListByName(String userName) {
        if (ObjectUtils.isEmpty(userName)) {
            throw new BusinessException("请求参数不允许为空");
        }
        Map<String, String> headers = HeaderUtil.headerInfo();
        JSONObject json = new JSONObject();
        UserDTO userDTO = UserUtil.getUserInfo();
        //String userId=userDTO.getUserId().toString();
        json.put("pageNum", 1);
        json.put("length", 999);
        /*List<String> deptList = new ArrayList<>();
        deptList.add(userDTO.getDeptCode());
        json.put("deptCodes", deptList);*/
        json.put("hasCert", Constant.STRING_1);
        List<String> orgCodes = new ArrayList<>();
        orgCodes.add(userDTO.getOrgCode());
        json.put("orgCodes", orgCodes);
        json.put("keyword", userName);
        json.put("searchType", Constant.STRING_1);
        String param = json.toJSONString();
        log.info("开始调用执法平台接口(getZfPeopleList)查询用户:" + param);
        String response = HttpUtil.createPost(url.concat(zfPeopleListUrl)).addHeaders(headers).body(param).execute().body();
        //log.info("执法平台接口(getZfPeopleList)返回信息:" + response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        List<HandleAssistVo> assistVoList = null;
        if (jsonObject.getIntValue("code") == 200) {
            JSONArray ja = jsonObject.getJSONObject("data").getJSONArray("data");
            if (ja == null || ja.size() == 0) {
                log.info("=======没有数据=======");
            }
            assistVoList = new ArrayList<>();
            for (int i = 0; i < ja.size(); i++) {
                JSONObject obj = (JSONObject) ja.get(i);
                if (!obj.getString("realName").contains(userName)) {
                    continue;
                }

                HandleAssistVo vo = new HandleAssistVo();
                vo.setDeptName(obj.getString("deptName"));
                vo.setLoginName(obj.getString("loginName"));
                vo.setDingDingId(obj.getString("zwdAccountId"));
                vo.setUserId(obj.getString("userId"));
                vo.setRealName(obj.getString("realName"));
                vo.setZfLicenseNo(obj.getString("zfCertNo"));
                vo.setOrgCode(obj.getString("orgCode"));
                vo.setOrgName(obj.getString("orgName"));
                assistVoList.add(vo);
            }
        }
        return assistVoList;
    }

    /**
     * 描述： 根据caseId获取重复违法次数
     *
     * @return {@link int}
     * @author: zhengqiang
     * @date: 2022/8/3
     * @param: caseId
     **/
    @Override
    public List<CaseMainReasonRepeatVo> getCaseRepeatPageList(CaseRepeatPageRequest pageRequest) {
        //查询配置年数
        String year = "'" + repeatCaseParamOfYears + " year'";
        pageRequest.setYear(year);
        if (ObjectUtils.isEmpty(pageRequest.getCaseReasonCodes())) {
            //案由处理
            List<CaseReasonMainRecordVo> caseReasonMainRecordList = caseReasonMainRecordService.getCaseReasonRecordListByCaseId(pageRequest.getCaseId());
            if (ObjectUtil.isNotEmpty(caseReasonMainRecordList) && caseReasonMainRecordList.size() > 0) {
                List<String> caseReasonCodes = caseReasonMainRecordList.stream().map(e -> e.getCaseReasonCode()).filter(code -> code != null).collect(Collectors.toList());
                pageRequest.setCaseReasonCodes(caseReasonCodes);
            }
        }

        //当事人处理
        List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfoVoList(pageRequest.getCaseId());
        if (!ObjectUtils.isEmpty(casePartiesRecords)) {
            List<String> partyIdentityCodes = casePartiesRecords.stream()
                    .map(e -> e.getPartyIdentityCode() + "_" + e.getPartyType() + "_" + StringUtils.defaultString(e.getPartyIdentityType()))
                    .collect(Collectors.toList());
            pageRequest.setPartyIdentityCodes(partyIdentityCodes);
        }

        List<CaseMainReasonRepeatVo> caseMainReasonRepeatVos = new ArrayList<>();
        if (!ObjectUtils.isEmpty(pageRequest.getCaseReasonCodes())) {
            PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getLength(), pageRequest.getOrderBy());
            caseMainReasonRepeatVos = caseMainInfoMapper.selectCaseRepeatListByReasonAndParties(pageRequest);
            caseMainReasonRepeatVos.forEach(vo -> {
                vo.setCaseTypeName(CaseTypeEnum.getValueByCode(vo.getCaseType()));
                //案由名称处理
                List<CaseReasonMainRecordVo> caseReasonMainRecordList = caseReasonMainRecordService.getCaseReasonRecordListByCaseId(vo.getCaseId());
                if (ObjectUtil.isNotEmpty(caseReasonMainRecordList) && caseReasonMainRecordList.size() > 0) {
                    String reasonName = caseReasonMainRecordList.stream().map(e -> e.getCaseReasonName()).filter(name -> name != null).collect(Collectors.joining(","));
                    vo.setCaseReasonName(reasonName);
                }
                //查询处罚决定书地址
                Example docRecord = new Example(CaseDocumentRecord.class);
                if (ObjectUtils.isEmpty(vo.getPunishDocumentNumber())) {
                    return;
                }
                docRecord.createCriteria().andEqualTo("caseId", vo.getCaseId()).andEqualTo("documentNumber", vo.getPunishDocumentNumber());
                List<CaseDocumentRecord> documentRecords = caseDocumentRecordMapper.selectByExample(docRecord);
                if (!ObjectUtils.isEmpty(documentRecords)) {
                    CaseDocumentRecord caseDocumentRecord = documentRecords.get(0);
                    String docUrl = !ObjectUtils.isEmpty(caseDocumentRecord.getDocumentUrlAfterSign()) ? caseDocumentRecord.getDocumentUrlAfterSign() : caseDocumentRecord.getDocumentUrlAfterSeal();
                    // 20230915 oss地址加密
                    vo.setDocumentUrl(FileEncryptionUtils.getEncryptFileNameByFileUrl(docUrl));
                }
            });
            return caseMainReasonRepeatVos;
        }
        return caseMainReasonRepeatVos;
    }

    /**
     * 不予立案保存
     *
     * @param caseSourceDetailDto
     * @return {@link int}
     * @author liyafeng
     * @date 2022/8/17
     */
    @Override
    public int saveNoCaseRegister(CaseSourceDetailDto caseSourceDetailDto) {
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourceDetailDto.getCaseSourceId());
        //保存存不予立案案件信息
        int num = saveCaseMainInfoNoRegister(caseSourceRegisterMainInfo);
        //保存办案人员信息
        saveCaseHandlePerson(caseSourceRegisterMainInfo);
        //saveCaseSourceFlow(caseSourceRegisterMainInfo);
        return num;
    }

    /**
     * 保存办案人员信息
     *
     * @param caseSourceRegisterMainInfo
     * @return
     * @author liyafeng
     * @date 2022/8/19
     */
    private void saveCaseHandlePerson(CaseSourceRegisterMainInfo caseSourceRegisterMainInfo) {
        //查询案件办案人员是否存在
        List<CaseHandlePersonRecord> caseHandlePersonRecordVos = caseHandlePersonRecordService.getCaseHandlePersonRecordList(caseSourceRegisterMainInfo.getId());
        if (null == caseHandlePersonRecordVos || caseHandlePersonRecordVos.size() == 0) {
            Example example = new Example(CaseSourceHandlePersonRecord.class);
            example.createCriteria().andEqualTo("caseSourceId", caseSourceRegisterMainInfo.getId());
            List<CaseSourceHandlePersonRecord> caseSourceHandlePersonRecords = caseSourceHandlePersonRecordMapper.selectByExample(example);
            if (null != caseSourceHandlePersonRecords && caseSourceHandlePersonRecords.size() > 0) {
                caseSourceHandlePersonRecords.forEach(caseSourceHandlePersonRecord -> {
                    CaseHandlePersonRecord caseHandlePersonRecord = new CaseHandlePersonRecord();
                    BeanUtils.copyProperties(caseSourceHandlePersonRecord, caseHandlePersonRecord);
                    caseHandlePersonRecord.setCaseId(caseSourceRegisterMainInfo.getId());
                    caseHandlePersonRecord.setStatus(Constant.STRING_1);
                    caseHandlePersonRecord.setAddTime(new Date());
                    caseHandlePersonRecordMapper.insert(caseHandlePersonRecord);

                });
            }
        }

    }

    /**
     * 案源流转日志保存
     *
     * @param caseSourceRegisterMainInfo
     * @return
     * @author liyafeng
     * @date 2022/8/17
     */
    private void saveCaseSourceFlow(CaseSourceRegisterMainInfo caseSourceRegisterMainInfo) {
        FlowCommonDto flowCommonDto = new FlowCommonDto();
        UserDTO userDTO = UserUtil.getUserInfo();
        flowCommonDto.setCaseSourceId(caseSourceRegisterMainInfo.getId());
        flowCommonDto.setStartPersonName(userDTO.getRealName());
        flowCommonDto.setStartPersonOrgName(userDTO.getOrgName());
        flowCommonDto.setFlowStartTime(new Date());
        flowCommonDto.setFlowEndTime(new Date());
        flowCommonDto.setStartPersonDeptName(userDTO.getDeptName());
        flowCommonDto.setFlowStageType(Constant.CASE_SOURCE_STAGE_BYLASP);
        caseSourceFlowRecordService.saveCommonFlowRecord(flowCommonDto);
    }

    /**
     * 保存不予立案信息
     *
     * @param caseSourceRegisterMainInfo
     * @return
     * @author liyafeng
     * @date 2022/8/17
     */
    private int saveCaseMainInfoNoRegister(CaseSourceRegisterMainInfo caseSourceRegisterMainInfo) {
        int num = 1;
        CaseMainInfoVo caseMainInfoVo = caseMainInfoMapper.selectCaseMainInfo(caseSourceRegisterMainInfo.getId());
        if (null != caseMainInfoVo) {
            if (!CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfoVo.getCaseStatus())) {
                throw new BusinessException("不予立案失败，已存在立案信息");
            }
            return num;
        } else {
            CaseMainInfo caseMainInfo = new CaseMainInfo();
            caseMainInfo.setId(caseSourceRegisterMainInfo.getId());
            caseMainInfo.setCaseName(caseSourceRegisterMainInfo.getCaseSourceName());
            caseMainInfo.setCaseStatus(CaseStatusEnum.PUNISH_NO_REGISTER.getCode());
            caseMainInfo.setCaseCreateTime(LocalDateTime.now());
            caseMainInfo.setBusiParamId(Constant.QS_BUSI_PARAM_ID);
            caseMainInfo.setCaseDeptCode(caseSourceRegisterMainInfo.getHandleDeptCode());
            caseMainInfo.setCaseDeptName(caseSourceRegisterMainInfo.getHandleDeptName());
            caseMainInfo.setCaseOrgCode(caseSourceRegisterMainInfo.getHandleOrgCode());
            caseMainInfo.setCaseOrgName(caseSourceRegisterMainInfo.getHandleOrgName());
            caseMainInfo.setCaseSource(CaseSourceEnum.getValueByCode(caseSourceRegisterMainInfo.getCaseSource()));
            caseMainInfo.setDataSource(ApiVisitDataSourceEnum.PUNISH_AY.getCode());
            caseMainInfo.setDataSourceServiceId(caseSourceRegisterMainInfo.getId());
            caseMainInfo.setLineCode(caseSourceRegisterMainInfo.getLineCode());
            caseMainInfo.setLineName(caseSourceRegisterMainInfo.getLineName());
            return caseMainInfoMapper.insert(caseMainInfo);
        }
    }

    /**
     * 描述： 检查转处罚保存处置回传结果
     *
     * @return {@link Result}
     * @author: zhengqiang
     * @date: 2022/8/19
     * @param: caseId
     **/
    @Override
    public Result sendDisposalBackResult(String caseId) {
        //检查转处罚的需要回传处置结果
        log.info("开始处理需要回传处置结果的案源");
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (ObjectUtils.isEmpty(caseMainInfo)) {
            log.warn("开始处理需要回传处置结果的案源: 案件不存在,caseId:{}", caseId);
            return Result.error("案件不存在");
        }
        //查询案源信息
        CaseSourceRegisterMainInfo mainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseId);

        if (ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(caseMainInfo.getDataSource())
                || (!ObjectUtils.isEmpty(mainInfo) && ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(mainInfo.getCaseSourceAppId()))) {
            log.info("开始检查转处罚的需要回传处置结果处理");
            DisposalBackResultDto backResultDto = new DisposalBackResultDto();
            backResultDto.setDisposalUid(caseId);
            if (!ObjectUtils.isEmpty(mainInfo)) {
                //检查转案源
                backResultDto.setDisposalUid(mainInfo.getCaseSourceAppServiceId());
            } else {
                //检查直接立案
                if (!ObjectUtils.isEmpty(caseMainInfo.getDataSourceServiceId()) && !caseMainInfo.getDataSourceServiceId().equals(caseId)) {
                    backResultDto.setDisposalUid(caseMainInfo.getDataSourceServiceId());
                }
            }
            backResultDto.setPunishUid(caseId);
            if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                //简易程序
                CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
                if (!ObjectUtils.isEmpty(caseMainDetailSimpleInfo)) {
                    backResultDto.setPunishCode(caseMainDetailSimpleInfo.getPunishDocumentNumber());
                }
            } else {
                //案件编号
                backResultDto.setPunishCode(caseMainInfo.getCaseNumber());
            }
            //立案时间
            String registerTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (!ObjectUtils.isEmpty(caseMainInfo.getCaseRegistTime())) {
                registerTime = caseMainInfo.getCaseRegistTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            backResultDto.setPunishTime(registerTime);
            backResultDto.setReceiveDeptCode(caseMainInfo.getCaseDeptCode());
            backResultDto.setReceiveDeptName(caseMainInfo.getCaseDeptName());
            //定死 5:已立案
            backResultDto.setDisposalStatus("5");
            log.info("检查转处罚的需要回传处置结果处理请求参数:{}", backResultDto);
            Result result = taskCenterService.saveDisposalBackResult(backResultDto);
            log.info("检查转处罚的需要回传处置结果处理返回结果:{}", result);
            return result;
        } else if (ApiVisitDataSourceEnum.TASKCENTER_TRANSFER.getCode().equals(caseMainInfo.getDataSource())
                || (!ObjectUtils.isEmpty(mainInfo) && ApiVisitDataSourceEnum.TASKCENTER_TRANSFER.getCode().equals(mainInfo.getCaseSourceAppId()))) {
            log.info("开始协同转处罚的需要回传处置结果处理");
            TripartiteStatusDto statusDto = new TripartiteStatusDto();
            statusDto.setRelUid(caseId);
            statusDto.setRelStatus(CaseSourceStatusEnum.REGISTERED.getIndex());
            statusDto.setRelStatusName(CaseSourceStatusEnum.REGISTERED.getName());
            if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus())) {
                statusDto.setRelStatus(CaseSourceStatusEnum.NO_REGISTERED.getIndex());
                statusDto.setRelStatusName(CaseSourceStatusEnum.NO_REGISTERED.getName());
            }
            Result result = taskCenterService.tripartiteStatusByRelUid(statusDto);
            log.info(" 修改协同的案件移送状态(协同)返回结果:{}", result);
            return result;
        } else {
            log.info("来源未配置结果回传, 无需处理");
        }
        return Result.success(Constant.STRING_SUCCESS_EN);
    }

    @Override
    public int modifyCaseRegisterInfo(CaseRegisterSaveDto saveDto) {
        //校验参数并处理数据
        String errorMsg = checkAndDealCaseRegisterInfo(saveDto);
        if (StringUtils.isNotEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        String caseId = saveDto.getCaseId();
        CaseMainInfoVo oldCaseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        //更新宽表数据
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        CaseMainDetailInfo oldDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        updateCaseMainDetailInfo.setCaseId(caseId);
        updateCaseMainDetailInfo.setId(oldDetailInfo.getId());
        updateCaseMainDetailInfo.setCaseHappenTime(BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime()));
        updateCaseMainDetailInfo.setCaseSourceId(saveDto.getCaseSourceId());
        updateCaseMainDetailInfo.setCaseHappenAddressDetail(saveDto.getCaseHappenAddress());
        updateCaseMainDetailInfo.setCaseHappenAddressAreaCode(saveDto.getCaseHappenAddressAreaCode());
        // updateCaseMainDetailInfo.setCaseHappenAddressDetailFull(saveDto.getCaseHappenAddressDetail());
        updateCaseMainDetailInfo.setCaseConciseCondition(saveDto.getCaseConciseCondition());
        //updateCaseMainDetailInfo.setUpdateTime(LocalDateTime.now());
        //修改文书不修改案件名称
        //  updateCaseMainDetailInfo.setCaseName(saveDto.getCaseName());
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
        //更新主表数据
        CaseMainInfo caseMainInfo = new CaseMainInfo();
        caseMainInfo.setId(saveDto.getCaseId());
        caseMainInfo.setCaseSource(saveDto.getCaseSource());

        //   caseMainInfo.setCaseName(saveDto.getCaseName());
        return caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);
    }

    /**
     * 检查转普通程序办案人员信息处理
     *
     * @param caseHandlePersonInfoDtoList
     * @param caseId
     * @param userInfo
     */
    private void dealCaseRegisterHandlePersonInfoOfCheck(List<CaseHandlePersonInfoDto> caseHandlePersonInfoDtoList, String caseId, UserDTO userInfo) {
        // 校验办案人员信息
        List<CaseHandlePersonInfoDto> mainHandlePersonList = caseHandlePersonInfoDtoList.stream().filter(e -> Constant.STRING_1.equals(e.getHandlePersonType())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(mainHandlePersonList) || mainHandlePersonList.size() < 1) {
            throw new BusinessException("主办人员不能为空");
        }

        //删除之前的办案人员
        Example example = new Example(CaseHandlePersonRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        caseHandlePersonRecordMapper.deleteByExample(example);
        for (CaseHandlePersonInfoDto handlePersonInfoDto : caseHandlePersonInfoDtoList) {
            CaseHandlePersonRecord caseHandlePersonRecord = new CaseHandlePersonRecord();
            BeanUtils.copyProperties(handlePersonInfoDto, caseHandlePersonRecord);
            caseHandlePersonRecord.setHandlePersonType(handlePersonInfoDto.getHandlePersonType());
            caseHandlePersonRecord.setDingId(handlePersonInfoDto.getDingId());
            if (ObjectUtil.isNotEmpty(handlePersonInfoDto.getHandlePersonId())) {
                String lawEnforcementCert = null;
                //检查转处罚有上级部门操作下级部门案件,用当前用户token获取部门会有问题
                if (ObjectUtil.isNotEmpty(handlePersonInfoDto.getHandleOrgCode())) {
                    lawEnforcementCert = xzzfInterfaceService.getLawEnforcementCertWithUserIdAndOrgCode(handlePersonInfoDto.getHandlePersonId(), handlePersonInfoDto.getHandleOrgCode());
                } else {
                    lawEnforcementCert = xzzfInterfaceService.getLawEnforcementCertWithUserId(handlePersonInfoDto.getHandlePersonId());
                }

                if (ObjectUtil.isEmpty(lawEnforcementCert)) {
                    throw new BusinessException("办案人员" + handlePersonInfoDto.getHandlePersonName() + "的执法证为空!");
                }
                caseHandlePersonRecord.setLawEnforcementCert(lawEnforcementCert);
                handlePersonInfoDto.setLawEnforcementCert(lawEnforcementCert);
            }
            //  签名校验
            String handlePersonSignPic = null;
            try {
                handlePersonSignPic = commonService.getHandleSignData(handlePersonInfoDto.getHandlePersonId());
            } catch (Exception e) {
                e.printStackTrace();
                if ("true".equals(isCheckHandleSign)) {
                    if (ObjectUtil.isEmpty(handlePersonSignPic)) {
                        throw new BusinessException("因未获取承办人员" + handlePersonInfoDto.getHandlePersonName() + "有效签名信息，无法提交");
                    }
                }
            }
            caseHandlePersonRecord.setHandleSignPic(handlePersonSignPic);
            caseHandlePersonRecord.setId(BaseUtil.createUid());
            caseHandlePersonRecord.setCaseId(caseId);
            caseHandlePersonRecord.setHandleOrgCode(userInfo.getOrgCode());
            caseHandlePersonRecord.setHandleOrgName(userInfo.getOrgName());
            caseHandlePersonRecord.setHandleOrgTel(userInfo.getTelPhone());
            caseHandlePersonRecord.setHandleDeptCode(userInfo.getDeptCode());
            caseHandlePersonRecord.setHandleDeptName(userInfo.getDeptName());
            caseHandlePersonRecord.setHandleDeptTel(userInfo.getTelPhone());
            caseHandlePersonRecord.setHandlePersonTel(handlePersonInfoDto.getHandlePersonTel());
            caseHandlePersonRecord.setStatus(Constant.STRING_1);
            caseHandlePersonRecord.setAddTime(new Date());
            caseHandlePersonRecordMapper.insertSelective(caseHandlePersonRecord);
        }

    }


    /**
     * 【V1.12.1】描述：简案快办保存立案登记
     *
     * @return {@link CaseRegisterSaveVo}
     * @author: zhengqiang
     * @date: 2023/8/15
     * @param: saveDto
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CaseRegisterSaveVo saveFastCaseRegister(FastCaseRegisterSaveDto fastCaseRegisterSaveDto) {
        String operateType = fastCaseRegisterSaveDto.getOperateType();
        //暂存
        if (Constant.STRING_0.equals(operateType)) {
            return saveFastCaseRegisterTemporary(fastCaseRegisterSaveDto);
        }
        //下一步
        UserDTO userInfo = UserUtil.getUserInfo();
        CaseRegisterSaveDto saveDto = new CaseRegisterSaveDto();
        //校验参数并处理数据
        String errorMsg = checkAndDealFastCaseRegisterInfo(fastCaseRegisterSaveDto, saveDto);
        if (StringUtils.isNotEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userInfo.getOrgCode(), userInfo.getDeptCode());
        if (ObjectUtil.isEmpty(saveDto.getOrgStandardName())) {
            if (ObjectUtil.isEmpty(sysDepartParam.getOrgStandardName())) {
                throw new BusinessException("办案单位暂未维护文书抬头");
            } else {
                saveDto.setOrgStandardName(sysDepartParam.getOrgStandardName());
            }
        }

        saveDto.setFastPartyType(fastCaseRegisterSaveDto.getPartyType());
        //简案快办案件默认数据初始化
        dealFastCaseMainDefaultData(saveDto, sysDepartParam);
        //下一步设置简案快办表单为快办告知
        saveDto.setSimpleFormType(SimpleFormTypeEnum.FAST_INFORM.getCode());
        //获取领域下业务参数
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        request.setApplyFieldCode(saveDto.getCaseTerritoryCode());
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        //获取流程信息--调用公用接口
        request.setCaseType(saveDto.getCaseType());
        Map<String, Object> resultMap = configBusiParamMainService.getRelationWorkflowInfo(request);
        //业务参数Id
        String busiParamId = configBusiParamMainList.get(0).getId();
        saveDto.setBusiParamId(busiParamId);

        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, DocumentKindEnum.DOC_KIND_LASPB.getCode());
        String workFlowCode = resultMap.get("WORKFLOWCODE").toString();
        List<CaseReasonMainRecord> caseReasonMainRecords = new ArrayList<>();
        List<CasePartiesRecord> partiesRecords = new ArrayList<>();


        //1、处理立案登记-主表、宽表信息 内部方法普通调用时代理不生效，使用@EnableAspectJAutoProxy开启自动代理
        ((CaseRegisterServiceImpl) AopContext.currentProxy()).dealCaseRegisterMainInfo(saveDto, workFlowCode, userInfo);
        String caseId = saveDto.getCaseId();
        //2、处理案由信息
        dealCaseRegisterCaseReasonInfo(saveDto.getCaseReasonInfoList(), caseId, caseReasonMainRecords);
        //3、处理办案人员信息
        dealCaseRegisterHandlePersonInfo(saveDto.getHandlePersonInfoList(), caseId, userInfo);
        //4、处理当事人信息
        ((CaseRegisterServiceImpl) AopContext.currentProxy()).dealCaseRegisterPartiesInfo(saveDto, workFlowCode, partiesRecords);

        //5、处理案件详情补充表
        dealCaseRegisterAuxiliaryInfo(saveDto, caseReasonMainRecords, partiesRecords);

        //6.调用文书公共接口生成文书记录
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        commonOperateSaveDto.setCaseId(saveDto.getCaseId());
        commonOperateSaveDto.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        commonOperateSaveDto.setIsUpdateRelationTable(Constant.STRING_0);
        commonOperateSaveDto.setPartyId(saveDto.getPartyIds());
        saveDto.setOrgStandardName(commonService.getOrgStandardNameByOrgCode(userInfo.getOrgCode(), userInfo.getDeptCode()));
        commonOperateSaveDto.setDataMap(BaseUtil.javaToMap(saveDto));
        log.info("----------进入文书生成公共服务saveDocInfo--------------");
        Map<String, Object> docResultMap = stageDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
        String status = MapUtils.getString(docResultMap, "success", "");
        String msg = MapUtils.getString(docResultMap, "msg", "");
        if (!"true".equals(status)) {
            log.info("----------文书生成公共服务saveDocInfo------报错---" + docResultMap);
            throw new BusinessException(msg);
        }
        //生成简案快办告知书
        FastCaseRegisterInfoQueryDto queryDto = new FastCaseRegisterInfoQueryDto();
        queryDto.setCaseId(caseId);
        fastCaseRegisterService.createFastCaseNoticeDocument(queryDto);
        //下一步删除暂存表
        caseTemporaryRecordService.removeTemporary(saveDto.getCaseId(), configBusiParamDocumentInfo.getDocumentCatalogCode());

        // 证据库案件信息同步对接
        if (SpringContextUtil.checkIsPrdProfile() || SpringContextUtil.checkIsDevProfile()) {
            //未生成案件编号, 编号也传caseId
            evidenceInventoryService.saveEvent(caseId, caseId);
        }
        //更新快办文书partyId
        dealFastCaseDocumentPartyId(caseId, partiesRecords.get(0).getPartyId());

        CaseRegisterSaveVo saveVo = new CaseRegisterSaveVo();
        saveVo.setCaseId(saveDto.getCaseId());
        saveVo.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        return saveVo;
    }

    /**
     * 更新快办文书partyId
     *
     * @param caseId
     * @param partyId
     */
    private void dealFastCaseDocumentPartyId(String caseId, String partyId) {
        //更新之前做的文书的partyId
        List<CaseDocumentCatalogChainDetailVo> caseDocumentCatalogChainDetailVos = caseDocumentRecordMapper.selectAllCaseDocumentInfoEffectiveByCaseId(caseId);
        for (CaseDocumentCatalogChainDetailVo detailVo : caseDocumentCatalogChainDetailVos) {
            String documentKindCode = detailVo.getDocumentKindCode();
            //排除立案审批表
            if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode)) {
                continue;
            }
            CaseDocumentRecord record = new CaseDocumentRecord();
            record.setId(detailVo.getDocumentId());
            record.setPartyId(partyId);
            caseDocumentRecordMapper.updateByPrimaryKeySelective(record);

            if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(documentKindCode)) {
                //送达地址确认书详情表更新partyId
                Example queryExample = new Example(CaseDocumentSendinfoConfirm.class);
                queryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", Constant.INTEGER_1);
                List<CaseDocumentSendinfoConfirm> caseDocumentSendinfoConfirms = caseDocumentSendinfoConfirmMapper.selectByExample(queryExample);
                if (ObjectUtil.isNotEmpty(caseDocumentSendinfoConfirms)) {
                    for (CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm : caseDocumentSendinfoConfirms) {
                        CaseDocumentSendinfoConfirm updateCaseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
                        updateCaseDocumentSendinfoConfirm.setId(caseDocumentSendinfoConfirm.getId());
                        updateCaseDocumentSendinfoConfirm.setPartyId(partyId);
                        caseDocumentSendinfoConfirmMapper.updateByPrimaryKeySelective(updateCaseDocumentSendinfoConfirm);
                    }
                }
            }
        }
        //更新关联文书partyId
        Example example = new Example(CaseRelatedDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        List<CaseRelatedDocumentRecord> caseRelatedDocumentRecords = caseRelatedDocumentRecordMapper.selectByExample(example);
        if (ObjectUtil.isEmpty(caseRelatedDocumentRecords)) {
            for (CaseRelatedDocumentRecord caseRelatedDocumentRecord : caseRelatedDocumentRecords) {
                CaseRelatedDocumentRecord relatedDocumentRecord = new CaseRelatedDocumentRecord();
                relatedDocumentRecord.setId(caseRelatedDocumentRecord.getId());
                relatedDocumentRecord.setPartyId(partyId);
                caseRelatedDocumentRecordMapper.updateByPrimaryKeySelective(relatedDocumentRecord);
            }
        }
    }


    /**
     * 【V1.12.1】描述：简案快办暂存
     *
     * @return {@link CaseRegisterSaveVo}
     * @author: zhengqiang
     * @date: 2023/8/17
     * @param: fastCaseRegisterSaveDto
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CaseRegisterSaveVo saveFastCaseRegisterTemporary(FastCaseRegisterSaveDto fastCaseRegisterSaveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        CaseRegisterSaveDto saveDto = new CaseRegisterSaveDto();
        BeanUtils.copyProperties(fastCaseRegisterSaveDto, saveDto);
        saveDto.setFastPartyType(fastCaseRegisterSaveDto.getPartyType());
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userInfo.getOrgCode(), userInfo.getDeptCode());

        //当事人处理
        List<CaseRegisterPartiesPersonInfoDto> fastPartiesPersonInfoList = new ArrayList<>();
        List<CaseRegisterPartiesLegalInfoDto> fastPartiesLegalInfoList = new ArrayList<>();
        CaseRegisterPartiesPersonInfoDto partiesPersonInfo = fastCaseRegisterSaveDto.getPartiesPersonInfo();
        CaseRegisterPartiesLegalInfoDto partiesLegalInfo = fastCaseRegisterSaveDto.getPartiesLegalInfo();
        if (ObjectUtil.isNotEmpty(partiesPersonInfo)) {
            partiesPersonInfo.setWasPlus(null);
        }
        if (!CustomCheckParamUtil.isFieldsNull(partiesPersonInfo)) {
            fastPartiesPersonInfoList.add(partiesPersonInfo);
        }
        if (!CustomCheckParamUtil.isFieldsNull(partiesLegalInfo)) {
            fastPartiesLegalInfoList.add(partiesLegalInfo);
        }
        saveDto.setPartiesPersonInfoList(fastPartiesPersonInfoList);
        saveDto.setPartiesLegalInfoList(fastPartiesLegalInfoList);

        dealFastCaseMainDefaultData(saveDto, sysDepartParam);

        //1、获取领域下业务参数
        //获取流程信息--调用公用接口
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        //修改为选择的条线领域
        request.setApplyFieldCode(saveDto.getCaseTerritoryCode());
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        //业务参数Id
        String busiParamId = configBusiParamMainList.get(0).getId();
        ConfigBusiParamDocumentInfo paramDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, DocumentKindEnum.DOC_KIND_LASPB.getCode());
        String caseId = saveDto.getCaseId();

        //1.添加案件主表
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        boolean flag = false;
        if (caseMainInfo == null) {
            caseMainInfo = new CaseMainInfo();
            caseMainInfo.setId(BaseUtil.createUid());
            saveDto.setCaseId(caseMainInfo.getId());
            caseId = caseMainInfo.getId();
            flag = true;
        }
        caseMainInfo.setLineName(saveDto.getLineName());
        caseMainInfo.setLineCode(saveDto.getLineCode());
        caseMainInfo.setBusiParamId(busiParamId);
        caseMainInfo.setCaseName(saveDto.getCaseName());
        caseMainInfo.setCaseType(saveDto.getCaseType());
        caseMainInfo.setCaseSource(saveDto.getCaseSource());
        //暂存
        caseMainInfo.setCaseStatus(CaseStatusEnum.TEMP.getCode());
        caseMainInfo.setCaseOrgCode(userInfo.getOrgCode());
        caseMainInfo.setCaseOrgName(userInfo.getOrgName());
        caseMainInfo.setCaseDeptCode(userInfo.getDeptCode());
        caseMainInfo.setCaseDeptName(userInfo.getDeptName());
        caseMainInfo.setCaseCurrentStageName("暂存");
        caseMainInfo.setCaseCreateTime(LocalDateTime.now());

        //设置主办协办人员信息
        List<CaseHandlePersonInfoDto> handlePersonInfoList = saveDto.getHandlePersonInfoList();
        if (ObjectUtil.isNotEmpty(handlePersonInfoList)) {
            for (CaseHandlePersonInfoDto caseHandlePersonInfoDto : handlePersonInfoList) {
                if (HandlePersonTypeEnum.MAIN.getCode().equals(caseHandlePersonInfoDto.getHandlePersonType())) {
                    caseMainInfo.setHandlePersonMainId(caseHandlePersonInfoDto.getHandlePersonId());
                    caseMainInfo.setHandlePersonMainName(caseHandlePersonInfoDto.getHandlePersonName());
                } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(caseHandlePersonInfoDto.getHandlePersonType())) {
                    caseMainInfo.setHandlePersonAssistId(caseHandlePersonInfoDto.getHandlePersonId());
                    caseMainInfo.setHandlePersonAssistName(caseHandlePersonInfoDto.getHandlePersonName());
                }
            }
        }

        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        BeanUtils.copyProperties(saveDto, caseMainDetailInfo);
        if (ObjectUtil.isNotEmpty(saveDto.getCaseHappenTime())) {
            caseMainDetailInfo.setCaseHappenTime(BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime()));
        }
        caseMainDetailInfo.setCaseSourceId(saveDto.getCaseSourceId());
        //暂存设置表单为事项选择
        caseMainDetailInfo.setSimpleFormType(SimpleFormTypeEnum.ITEM_SELECT.getCode());
        if (ObjectUtil.isEmpty(saveDto.getCaseName())) {
            caseMainDetailInfo.setCaseName("-");
        }
        if (flag) {
            caseMainInfoMapper.insertSelective(caseMainInfo);
            //新增宽表
            caseMainDetailInfo.setCreateTime(LocalDateTime.now());
            caseMainDetailInfo.setId(BaseUtil.createUid());
            caseMainDetailInfo.setCaseId(caseMainInfo.getId());
            caseMainDetailInfoMapper.insertSelective(caseMainDetailInfo);
        } else {
            caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);
            //更新宽表数据
            CaseMainDetailInfo oldDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
            caseMainDetailInfo.setCaseId(caseMainInfo.getId());
            caseMainDetailInfo.setId(oldDetailInfo.getId());
            caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
        }
        //处理办案人员
        dealFastCaseRegisterHandlePersonInfo(saveDto.getHandlePersonInfoList(), caseId, userInfo);
        //处理当事人信息
        dealFastCaseRegisterPartiesInfo(saveDto);
        //查询并更新文书记录表的文书内容
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, paramDocumentInfo.getDocumentCatalogCode());
        if (ObjectUtil.isNotEmpty(caseDocumentRecord)) {
            Example updateE = new Example(CaseDocumentRecord.class);
            updateE.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("documentCatalogCode", caseDocumentRecord.getDocumentCatalogCode());
            CaseDocumentRecord newCaseDocumentRecord = new CaseDocumentRecord();
            newCaseDocumentRecord.setDocumentContent(JSONObject.toJSONString(saveDto));
            //设置文书为草稿状态
            newCaseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.DRAFT.getCode());
            caseDocumentRecordMapper.updateByExampleSelective(newCaseDocumentRecord, updateE);
        }

        //删除原暂存表数据并添加到暂存表
        caseTemporaryRecordService.removeTemporary(saveDto.getCaseId(), paramDocumentInfo.getDocumentCatalogCode());
        CaseTemporaryRecord record = new CaseTemporaryRecord();
        record.setId(BaseUtil.createUid());
        record.setCaseId(saveDto.getCaseId());
        record.setContent(JSONObject.toJSONString(saveDto));
        record.setAddUser(userInfo.getLoginName());
        record.setCreateTime(LocalDateTime.now());
        record.setDocumentCatalogCode(paramDocumentInfo.getDocumentCatalogCode());
        caseTemporaryRecordMapper.insertSelective(record);

        CaseRegisterSaveVo saveVo = new CaseRegisterSaveVo();
        saveVo.setCaseId(saveDto.getCaseId());
        saveVo.setDocumentCatalogCode(paramDocumentInfo.getDocumentCatalogCode());
        return saveVo;
    }

    /**
     *
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CaseRegisterSaveVo savCaseRegisterTemporary(RegisterSaveDto fastCaseRegisterSaveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        CaseRegisterSaveDto saveDto = new CaseRegisterSaveDto();
        BeanUtils.copyProperties(fastCaseRegisterSaveDto, saveDto);
        saveDto.setFastPartyType(fastCaseRegisterSaveDto.getPartyType());
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userInfo.getOrgCode(), userInfo.getDeptCode());

        //当事人处理
        List<CaseRegisterPartiesPersonInfoDto> fastPartiesPersonInfoList = new ArrayList<>();
        List<CaseRegisterPartiesLegalInfoDto> fastPartiesLegalInfoList = new ArrayList<>();
//        CaseRegisterPartiesPersonInfoDto partiesPersonInfo = fastCaseRegisterSaveDto.getPartiesPersonInfo();
//        CaseRegisterPartiesLegalInfoDto partiesLegalInfo = fastCaseRegisterSaveDto.getPartiesLegalInfo();
//        if (ObjectUtil.isNotEmpty(partiesPersonInfo)) {
//            partiesPersonInfo.setWasPlus(null);
//        }
//        if (!CustomCheckParamUtil.isFieldsNull(partiesPersonInfo)) {
//            fastPartiesPersonInfoList.add(partiesPersonInfo);
//        }
//        if (!CustomCheckParamUtil.isFieldsNull(partiesLegalInfo)) {
//            fastPartiesLegalInfoList.add(partiesLegalInfo);
//        }
//        saveDto.setPartiesPersonInfoList(fastPartiesPersonInfoList);
//        saveDto.setPartiesLegalInfoList(fastPartiesLegalInfoList);

        dealCaseMainDefaultData(saveDto, sysDepartParam);

        //1、获取领域下业务参数
        //获取流程信息--调用公用接口
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        //修改为选择的条线领域
        request.setApplyFieldCode(saveDto.getCaseTerritoryCode());
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        //业务参数Id
        String busiParamId = configBusiParamMainList.get(0).getId();
        ConfigBusiParamDocumentInfo paramDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, DocumentKindEnum.DOC_KIND_LASPB.getCode());
        String caseId = saveDto.getCaseId();

        //1.添加案件主表
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        boolean flag = false;
        if (caseMainInfo == null) {
            caseMainInfo = new CaseMainInfo();
            caseMainInfo.setId(BaseUtil.createUid());
            saveDto.setCaseId(caseMainInfo.getId());
            caseId = caseMainInfo.getId();
            flag = true;
        }
        caseMainInfo.setLineName(saveDto.getLineName());
        caseMainInfo.setLineCode(saveDto.getLineCode());
        caseMainInfo.setBusiParamId(busiParamId);
        caseMainInfo.setCaseName(saveDto.getCaseName());
        caseMainInfo.setCaseType(saveDto.getCaseType());
        caseMainInfo.setCaseSource(saveDto.getCaseSource());
        //暂存
        caseMainInfo.setCaseStatus(CaseStatusEnum.TEMP.getCode());
        caseMainInfo.setCaseOrgCode(userInfo.getOrgCode());
        caseMainInfo.setCaseOrgName(userInfo.getOrgName());
        caseMainInfo.setCaseDeptCode(userInfo.getDeptCode());
        caseMainInfo.setCaseDeptName(userInfo.getDeptName());
        caseMainInfo.setCaseCurrentStageName("暂存");
        caseMainInfo.setCaseCreateTime(LocalDateTime.now());

        //设置主办协办人员信息
        List<CaseHandlePersonInfoDto> handlePersonInfoList = saveDto.getHandlePersonInfoList();
        if (ObjectUtil.isNotEmpty(handlePersonInfoList)) {
            for (CaseHandlePersonInfoDto caseHandlePersonInfoDto : handlePersonInfoList) {
                if (HandlePersonTypeEnum.MAIN.getCode().equals(caseHandlePersonInfoDto.getHandlePersonType())) {
                    caseMainInfo.setHandlePersonMainId(caseHandlePersonInfoDto.getHandlePersonId());
                    caseMainInfo.setHandlePersonMainName(caseHandlePersonInfoDto.getHandlePersonName());
                } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(caseHandlePersonInfoDto.getHandlePersonType())) {
                    caseMainInfo.setHandlePersonAssistId(caseHandlePersonInfoDto.getHandlePersonId());
                    caseMainInfo.setHandlePersonAssistName(caseHandlePersonInfoDto.getHandlePersonName());
                }
            }
        }

        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        BeanUtils.copyProperties(saveDto, caseMainDetailInfo);
        if (ObjectUtil.isNotEmpty(saveDto.getCaseHappenTime())) {
            caseMainDetailInfo.setCaseHappenTime(BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime()));
        }
        caseMainDetailInfo.setCaseSourceId(saveDto.getCaseSourceId());
        //暂存设置表单为事项选择
        caseMainDetailInfo.setSimpleFormType(SimpleFormTypeEnum.ITEM_SELECT.getCode());
        if (ObjectUtil.isEmpty(saveDto.getCaseName())) {
            caseMainDetailInfo.setCaseName("-");
        }
        if (flag) {
            caseMainInfoMapper.insertSelective(caseMainInfo);
            //新增宽表
            caseMainDetailInfo.setCreateTime(LocalDateTime.now());
            caseMainDetailInfo.setId(BaseUtil.createUid());
            caseMainDetailInfo.setCaseId(caseMainInfo.getId());
            caseMainDetailInfoMapper.insertSelective(caseMainDetailInfo);
        } else {
            caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);
            //更新宽表数据
            CaseMainDetailInfo oldDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
            caseMainDetailInfo.setCaseId(caseMainInfo.getId());
            caseMainDetailInfo.setId(oldDetailInfo.getId());
            caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
        }
        //处理办案人员
        dealFastCaseRegisterHandlePersonInfo(saveDto.getHandlePersonInfoList(), caseId, userInfo);
        //处理当事人信息
        dealFastCaseRegisterPartiesInfo(saveDto);
        //查询并更新文书记录表的文书内容
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, paramDocumentInfo.getDocumentCatalogCode());
        if (ObjectUtil.isNotEmpty(caseDocumentRecord)) {
            Example updateE = new Example(CaseDocumentRecord.class);
            updateE.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("documentCatalogCode", caseDocumentRecord.getDocumentCatalogCode());
            CaseDocumentRecord newCaseDocumentRecord = new CaseDocumentRecord();
            newCaseDocumentRecord.setDocumentContent(JSONObject.toJSONString(saveDto));
            //设置文书为草稿状态
            newCaseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.DRAFT.getCode());
            caseDocumentRecordMapper.updateByExampleSelective(newCaseDocumentRecord, updateE);
        }

        //删除原暂存表数据并添加到暂存表
        caseTemporaryRecordService.removeTemporary(saveDto.getCaseId(), paramDocumentInfo.getDocumentCatalogCode());
        CaseTemporaryRecord record = new CaseTemporaryRecord();
        record.setId(BaseUtil.createUid());
        record.setCaseId(saveDto.getCaseId());
        record.setContent(JSONObject.toJSONString(saveDto));
        record.setAddUser(userInfo.getLoginName());
        record.setCreateTime(LocalDateTime.now());
        record.setDocumentCatalogCode(paramDocumentInfo.getDocumentCatalogCode());
        caseTemporaryRecordMapper.insertSelective(record);

        CaseRegisterSaveVo saveVo = new CaseRegisterSaveVo();
        saveVo.setCaseId(saveDto.getCaseId());
        saveVo.setDocumentCatalogCode(paramDocumentInfo.getDocumentCatalogCode());
        return saveVo;
    }

    /**
     * 【V1.12.1】描述： 查询简案快办暂存数据
     *
     * @return {@link FastCaseRegisterInfoVo}
     * @author: zhengqiang
     * @date: 2023/8/17
     * @param: queryDto
     **/
    @Override
    public FastCaseRegisterInfoVo getFastCaseRegisterInfo(FastCaseRegisterInfoQueryDto queryDto) {
        FastCaseRegisterInfoVo registerInfoVo = new FastCaseRegisterInfoVo();
        String caseId = queryDto.getCaseId();
        //立案审批表文书种类
        String kindCode = DocumentKindEnum.DOC_KIND_LASPB.getCode();
        String documentCatalogCode;
        List<ConfigBusiParamDocumentInfo> configList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId, null, kindCode);
        if (!ObjectUtils.isEmpty(configList)) {
            documentCatalogCode = configList.get(Constant.INTEGER_0).getDocumentCatalogCode();
        } else {
            throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",kindCode:" + kindCode);
        }
        String content = null;
        //查询暂存表是否有数据
        Example example = new Example(CaseTemporaryRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentCatalogCode", documentCatalogCode);
        List<CaseTemporaryRecord> list = caseTemporaryRecordMapper.selectByExample(example);
        if (ObjectUtil.isNotEmpty(list)) {
            content = list.get(0).getContent();
        } else {
            //未暂存,则查询案件信息
            CaseDocumentRecordDto recordDto = caseDocumentRecordService.getCaseDocumentRecordByKindCode(queryDto.getCaseId(), kindCode);
            if (ObjectUtil.isEmpty(recordDto)) {
                return registerInfoVo;
            }
            content = recordDto.getDocumentContent();
        }

        if (ObjectUtil.isNotEmpty(content)) {
            JSONObject jsonObj = JSONObject.parseObject(content);
            CaseRegisterInfoVo caseRegisterInfoVo = JSONObject.toJavaObject(jsonObj, CaseRegisterInfoVo.class);
            BeanUtils.copyProperties(caseRegisterInfoVo, registerInfoVo);
            registerInfoVo.setCaseType(CaseTypeEnum.FAST_PROCEDURE.getCode());
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
            registerInfoVo.setSimpleFormType(caseMainDetailInfo.getSimpleFormType());
            String fastPartyType = caseRegisterInfoVo.getFastPartyType();
            //当事人类型处理
            List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoList = caseRegisterInfoVo.getPartiesPersonInfoList();
            if (ObjectUtil.isNotEmpty(partiesPersonInfoList)) {
                registerInfoVo.setPartiesPersonInfo(partiesPersonInfoList.get(Constant.INTEGER_0));
                if (ObjectUtil.isEmpty(fastPartyType)) {
                    fastPartyType = PartyTypeEnum.PERSON.getCode();
                }
            }
            List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoList = caseRegisterInfoVo.getPartiesLegalInfoList();
            if (ObjectUtil.isNotEmpty(partiesLegalInfoList)) {
                registerInfoVo.setPartiesLegalInfo(partiesLegalInfoList.get(Constant.INTEGER_0));
                if (ObjectUtil.isEmpty(fastPartyType)) {
                    fastPartyType = PartyTypeEnum.LEGAL.getCode();
                }
            }
            registerInfoVo.setPartyType(fastPartyType);
        }

        return registerInfoVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CaseRegisterSaveVo saveCaseRegisterApp(RegisterSaveDto dto) {
        String operateType = dto.getOperateType();
        //暂存
        if (Constant.STRING_0.equals(operateType)) {
            return savCaseRegisterTemporary(dto);
        }
        //下一步
        UserDTO userInfo = UserUtil.getUserInfo();
        CaseRegisterSaveDto saveDto = new CaseRegisterSaveDto();
        //校验参数并处理数据
        FastCaseRegisterSaveDto fastCaseRegisterSaveDto = new FastCaseRegisterSaveDto();
        BeanUtils.copyProperties(dto, fastCaseRegisterSaveDto);
        BeanUtils.copyProperties(dto, saveDto);
        String errorMsg = checkAndDealCaseRegisterInfo(saveDto);
        if (StringUtils.isNotEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        // 案源信息
        saveDto.setCaseSourceId(dto.getCaseSourceId());
        saveDto.setCaseSource(dto.getCaseSource());
        saveDto.setCaseName(dto.getCaseName());
        saveDto.setCaseConciseCondition(dto.getCaseConciseCondition());
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userInfo.getOrgCode(), userInfo.getDeptCode());
        if (ObjectUtil.isEmpty(saveDto.getOrgStandardName())) {
            if (ObjectUtil.isEmpty(sysDepartParam.getOrgStandardName())) {
                throw new BusinessException("办案单位暂未维护文书抬头");
            } else {
                saveDto.setOrgStandardName(sysDepartParam.getOrgStandardName());
            }
        }

        saveDto.setFastPartyType(fastCaseRegisterSaveDto.getPartyType());
        //默认数据初始化
        dealCaseMainDefaultData(saveDto, sysDepartParam);
        LineDTO lineDTO = xzzfInterfaceService.getLineInfoByLineCode(saveDto.getLineCode());
        saveDto.setCaseTerritoryCode(lineDTO.getTerritoryCode());
        saveDto.setCaseTerritoryName(lineDTO.getTerritoryName());
        //获取领域下业务参数
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userInfo.getAreaCode());
        request.setApplyFieldCode(saveDto.getCaseTerritoryCode());
        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
        //获取流程信息--调用公用接口
        request.setCaseType(saveDto.getCaseType());
        Map<String, Object> resultMap = configBusiParamMainService.getRelationWorkflowInfo(request);
        //业务参数Id
        String busiParamId = configBusiParamMainList.get(0).getId();
        saveDto.setBusiParamId(busiParamId);

        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, DocumentKindEnum.DOC_KIND_LASPB.getCode());
        String workFlowCode = resultMap.get("WORKFLOWCODE").toString();
        List<CaseReasonMainRecord> caseReasonMainRecords = new ArrayList<>();
        List<CasePartiesRecord> partiesRecords = new ArrayList<>();


        //1、处理立案登记-主表、宽表信息 内部方法普通调用时代理不生效，使用@EnableAspectJAutoProxy开启自动代理
        ((CaseRegisterServiceImpl) AopContext.currentProxy()).dealCaseRegisterMainInfo(saveDto, workFlowCode, userInfo);
        String caseId = saveDto.getCaseId();
        //2、处理案由信息
        dealCaseRegisterCaseReasonInfo(saveDto.getCaseReasonInfoList(), caseId, caseReasonMainRecords);
        //3、处理办案人员信息
        dealCaseRegisterHandlePersonInfo(saveDto.getHandlePersonInfoList(), caseId, userInfo);
        //4、处理当事人信息
        ((CaseRegisterServiceImpl) AopContext.currentProxy()).dealCaseRegisterPartiesInfo(saveDto, workFlowCode, partiesRecords);

        //5、处理案件详情补充表
        dealCaseRegisterAuxiliaryInfo(saveDto, caseReasonMainRecords, partiesRecords);

        //下一步删除暂存表
        caseTemporaryRecordService.removeTemporary(saveDto.getCaseId(), configBusiParamDocumentInfo.getDocumentCatalogCode());


        // 历史的
        //获取办案条线对应的领域
//        LineDTO lineDTO = xzzfInterfaceService.getLineInfoByLineCode(saveDto.getLineCode());
//        saveDto.setCaseTerritoryCode(lineDTO.getTerritoryCode());
//        saveDto.setCaseTerritoryName(lineDTO.getTerritoryName());
//        //获取领域下业务参数
//        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
//        request.setApplyAreaCode(userInfo.getAreaCode());
//        request.setApplyFieldCode(saveDto.getCaseTerritoryCode());
//        List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
//        //获取流程信息--调用公用接口
//        request.setCaseType(saveDto.getCaseType());
//        Map<String, Object> resultMap = configBusiParamMainService.getRelationWorkflowInfo(request);
//        //业务参数Id
//        String busiParamId = configBusiParamMainList.get(0).getId();
//        saveDto.setBusiParamId(busiParamId);
//
//        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, "LASPB");
//        String workFlowCode = resultMap.get("WORKFLOWCODE").toString();
//        List<CaseReasonMainRecord> caseReasonMainRecords = new ArrayList<>();
//        List<CasePartiesRecord> partiesRecords = new ArrayList<>();
//
//
//        //1、处理立案登记-主表、宽表信息 内部方法普通调用时代理不生效，使用@EnableAspectJAutoProxy开启自动代理
//        ((CaseRegisterServiceImpl) AopContext.currentProxy()).dealCaseRegisterMainInfo(caseRegisterSaveDto, workFlowCode, userInfo);
//        String caseId = saveDto.getCaseId();
//        // 非人社还走以前流程。
//        if (!Constant.HUMAN_SOCIETY_BARS_CODE.equals(saveDto.getLineCode().substring(0, 4))) {
//            //2、处理案由信息
//            dealCaseRegisterCaseReasonInfo(saveDto.getCaseReasonInfoList(), caseId, caseReasonMainRecords);
//        }
//        //3、处理办案人员信息
//        dealCaseRegisterHandlePersonInfo(saveDto.getHandlePersonInfoList(), caseId, userInfo);
//        //4、处理当事人信息
//        ((CaseRegisterServiceImpl) AopContext.currentProxy()).dealCaseRegisterPartiesInfo(caseRegisterSaveDto, workFlowCode, partiesRecords);
//        //5、处理附件
        dealCaseRegisterAppendixInfo(saveDto, configBusiParamDocumentInfo.getDocumentCatalogCode());
//        //6、处理案件详情补充表
//        dealCaseRegisterAuxiliaryInfo(caseRegisterSaveDto, caseReasonMainRecords, partiesRecords);
//        //7、处理关联文书
//        dealCaseRegisterRelatedDocumentInfo(caseRegisterSaveDto);
        //8.调用文书公共接口生成文书记录
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        commonOperateSaveDto.setCaseId(saveDto.getCaseId());
        commonOperateSaveDto.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        commonOperateSaveDto.setIsUpdateRelationTable(Constant.STRING_0);
        commonOperateSaveDto.setPartyId(saveDto.getPartyIds());
        saveDto.setOrgStandardName(commonService.getOrgStandardNameByOrgCode(userInfo.getOrgCode(), userInfo.getDeptCode()));
        commonOperateSaveDto.setDataMap(BaseUtil.javaToMap(saveDto));
        log.info("----------进入文书生成公共服务saveDocInfo--------------");
        Map<String, Object> docResultMap = stageDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
        String status = MapUtils.getString(docResultMap, "success", "");
        String msg = MapUtils.getString(docResultMap, "msg", "");
        if (!"true".equals(status)) {
            log.info("----------文书生成公共服务saveDocInfo------报错---" + docResultMap);
            throw new BusinessException(msg);
        }
        CaseRegisterSaveVo saveVo = new CaseRegisterSaveVo();
        saveVo.setCaseId(saveDto.getCaseId());
        saveVo.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        return saveVo;
    }

    /**
     * 移动端普通程序及默认数据处理
     **/
    private void dealCaseMainDefaultData(CaseRegisterSaveDto saveDto, SysDepartParam sysDepartParam) {
        //1.案件名称初始化
        //获取当事人信息
        String partyName = "";
        List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoList = saveDto.getPartiesPersonInfoList();
        List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoList = saveDto.getPartiesLegalInfoList();
        if (ObjectUtil.isNotEmpty(partiesPersonInfoList) && PartyTypeEnum.PERSON.getCode().equals(saveDto.getFastPartyType())) {
            CaseRegisterPartiesPersonInfoDto caseRegisterPartiesPersonInfoDto = partiesPersonInfoList.get(Constant.INTEGER_0);
            partyName = StrUtil.nullToEmpty(caseRegisterPartiesPersonInfoDto.getName());
        }
        if (ObjectUtil.isNotEmpty(partiesLegalInfoList) && PartyTypeEnum.LEGAL.getCode().equals(saveDto.getFastPartyType())) {
            CaseRegisterPartiesLegalInfoDto caseRegisterPartiesLegalInfoDto = partiesLegalInfoList.get(Constant.INTEGER_0);
            partyName = StrUtil.nullToEmpty(caseRegisterPartiesLegalInfoDto.getEntName());
        }
        //获取案由信息
        String caseReasonName = "";
        //违则
        String illegalBasis = "";
        List<CaseReasonInfoDto> caseReasonInfoList = saveDto.getCaseReasonInfoList();
        if (ObjectUtil.isNotEmpty(caseReasonInfoList)) {
            CaseReasonInfoDto reasonInfoDto = caseReasonInfoList.get(Constant.INTEGER_0);
            caseReasonName = BaseUtil.handleCaseReason(reasonInfoDto.getCaseReasonName());
            illegalBasis = reasonInfoDto.getIllegalBasis();
        }

        if (StringUtils.isEmpty(saveDto.getCaseName())) {
            //当事人名称 + "涉嫌" + 处罚事项(去除案由中的“对”和“的行政处罚”) + "案"
            String caseName = partyName + "涉嫌" + caseReasonName + "案";
            saveDto.setCaseName(caseName);
        }
//
//        //2.案件来源初始化, 默认巡查中发现
//        saveDto.setCaseSourceId(CaseSourceEnum.CASE_SOURCE_XCZFX.getCode());
//        saveDto.setCaseSource(CaseSourceEnum.CASE_SOURCE_XCZFX.getDes());

        //3.案件简要情况初始化
        //发现日期 + "，" + 当事人 + "在" + 案发地 + "实施" + 处罚事项(去除案由中的“对”和“的行政处罚”) + "的违法行为。涉嫌违反" + 罚则 + "。"
        if (StringUtils.isEmpty(saveDto.getCaseConciseCondition())) {
            String caseHappenAddress = saveDto.getCaseHappenAddress();
            String caseConciseCondition = saveDto.getCaseHappenTimeStr() + "，" + partyName + "在" + caseHappenAddress + "实施" + caseReasonName + "的违法行为。涉嫌违反" + illegalBasis + "。";
            saveDto.setCaseConciseCondition(caseConciseCondition);
        }


//        //4.设置条线及领域 todo 默认条线的问题要不要改.
//        //将条线配置组装成集合对象
//        List<LineCaseHandleInfoVo> lineCaseHandleInfoVos = sysDepartParamService.assembleLineConfigToList(sysDepartParam.getLineConfig());
//        if (ObjectUtil.isEmpty(lineCaseHandleInfoVos)) {
//            throw new BusinessException("办案单位暂未维护条线配置");
//        }
//        List<LineCaseHandleInfoVo> lineList = lineCaseHandleInfoVos.stream().filter(e ->
//                ObjectUtil.isNotEmpty(e.getLineCode()) && e.getLineCode().contains(TerritoryCodeEnum.ZHZF.getCode()) && Constant.STRING_1.equals(e.getLineCaseHandleStatusCode()))
//                .collect(Collectors.toList());
//
//        if (ObjectUtil.isEmpty(lineList)) {
//            throw new BusinessException("办案单位暂未维护条线配置");
//        }
//        LineCaseHandleInfoVo lineCaseHandleInfoVo = lineList.get(Constant.INTEGER_0);
//        saveDto.setLineCode(lineCaseHandleInfoVo.getLineCode());
//        saveDto.setLineName(lineCaseHandleInfoVo.getLineName());
//        saveDto.setCaseTerritoryCode(TerritoryCodeEnum.ZHZF.getCode());
//        saveDto.setCaseTerritoryName(TerritoryCodeEnum.ZHZF.getDes());

        //5.设置案件类型为普通程序
        saveDto.setCaseType(CaseTypeEnum.NORMAL_PROCEDURE.getCode());
        saveDto.setIsMobile(Constant.STRING_1);
    }

    /**
     * 【V1.12.1】描述： 简案快办立案默认数据处理
     *
     * @return
     * @author: zhengqiang
     * @date: 2023/8/15
     * @param: saveDto
     * @param: sysDepartParam
     **/
    private void dealFastCaseMainDefaultData(CaseRegisterSaveDto saveDto, SysDepartParam sysDepartParam) {
        //1.案件名称初始化
        //获取当事人信息
        String partyName = "";
        List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoList = saveDto.getPartiesPersonInfoList();
        List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoList = saveDto.getPartiesLegalInfoList();
        if (ObjectUtil.isNotEmpty(partiesPersonInfoList) && PartyTypeEnum.PERSON.getCode().equals(saveDto.getFastPartyType())) {
            CaseRegisterPartiesPersonInfoDto caseRegisterPartiesPersonInfoDto = partiesPersonInfoList.get(Constant.INTEGER_0);
            partyName = StrUtil.nullToEmpty(caseRegisterPartiesPersonInfoDto.getName());
        }
        if (ObjectUtil.isNotEmpty(partiesLegalInfoList) && PartyTypeEnum.LEGAL.getCode().equals(saveDto.getFastPartyType())) {
            CaseRegisterPartiesLegalInfoDto caseRegisterPartiesLegalInfoDto = partiesLegalInfoList.get(Constant.INTEGER_0);
            partyName = StrUtil.nullToEmpty(caseRegisterPartiesLegalInfoDto.getEntName());
        }
        //获取案由信息
        String caseReasonName = "";
        //违则
        String illegalBasis = "";
        List<CaseReasonInfoDto> caseReasonInfoList = saveDto.getCaseReasonInfoList();
        if (ObjectUtil.isNotEmpty(caseReasonInfoList)) {
            CaseReasonInfoDto reasonInfoDto = caseReasonInfoList.get(Constant.INTEGER_0);
            caseReasonName = BaseUtil.handleCaseReason(reasonInfoDto.getCaseReasonName());
            illegalBasis = reasonInfoDto.getIllegalBasis();
        }

        //当事人名称 + "涉嫌" + 处罚事项(去除案由中的“对”和“的行政处罚”) + "案"
        String caseName = partyName + "涉嫌" + caseReasonName + "案";
        saveDto.setCaseName(caseName);

        //2.案件来源初始化, 默认巡查中发现
        saveDto.setCaseSourceId(CaseSourceEnum.CASE_SOURCE_XCZFX.getCode());
        saveDto.setCaseSource(CaseSourceEnum.CASE_SOURCE_XCZFX.getDes());

        //3.案件简要情况初始化
        //发现日期 + "，" + 当事人 + "在" + 案发地 + "实施" + 处罚事项(去除案由中的“对”和“的行政处罚”) + "的违法行为。涉嫌违反" + 罚则 + "。"
        String caseHappenAddress = saveDto.getCaseHappenAddress();
        String caseConciseCondition = saveDto.getCaseHappenTimeStr() + "，" + partyName + "在" + caseHappenAddress + "实施" + caseReasonName + "的违法行为。涉嫌违反" + illegalBasis + "。";
        saveDto.setCaseConciseCondition(caseConciseCondition);

        //4.设置条线及领域
        //将条线配置组装成集合对象
        List<LineCaseHandleInfoVo> lineCaseHandleInfoVos = sysDepartParamService.assembleLineConfigToList(sysDepartParam.getLineConfig());
        if (ObjectUtil.isEmpty(lineCaseHandleInfoVos)) {
            throw new BusinessException("办案单位暂未维护条线配置");
        }
        List<LineCaseHandleInfoVo> lineList = lineCaseHandleInfoVos.stream().filter(e ->
                ObjectUtil.isNotEmpty(e.getLineCode()) && e.getLineCode().contains(TerritoryCodeEnum.ZHZF.getCode()) && Constant.STRING_1.equals(e.getLineCaseHandleStatusCode()))
                .collect(Collectors.toList());

        if (ObjectUtil.isEmpty(lineList)) {
            throw new BusinessException("办案单位不支持简案快办");
        }
        LineCaseHandleInfoVo lineCaseHandleInfoVo = lineList.get(Constant.INTEGER_0);
        saveDto.setLineCode(lineCaseHandleInfoVo.getLineCode());
        saveDto.setLineName(lineCaseHandleInfoVo.getLineName());
        saveDto.setCaseTerritoryCode(TerritoryCodeEnum.ZHZF.getCode());
        saveDto.setCaseTerritoryName(TerritoryCodeEnum.ZHZF.getDes());

        //5.设置案件类型为简案快办
        saveDto.setCaseType(CaseTypeEnum.FAST_PROCEDURE.getCode());
    }


    /**
     * 【V1.12.1】描述： 简案快办立案参数校验
     *
     * @return {@link String}
     * @author: zhengqiang
     * @date: 2023/8/16
     * @param: fastCaseRegisterSaveDto
     * @param: saveDto
     **/
    public String checkAndDealFastCaseRegisterInfo(FastCaseRegisterSaveDto fastCaseRegisterSaveDto, CaseRegisterSaveDto saveDto) {
        String errorMessage = "";
        if (ObjectUtil.isEmpty(fastCaseRegisterSaveDto.getCaseHappenTime())) {
            errorMessage = "案发时间不能为空";
            return errorMessage;
        }
        if (ObjectUtil.isEmpty(fastCaseRegisterSaveDto.getCaseHappenAddressDetail())) {
            errorMessage = "案件地不能为空";
            return errorMessage;
        }
        if (ObjectUtil.isEmpty(fastCaseRegisterSaveDto.getCaseHappenAddressAreaCode())) {
            errorMessage = "案发地区域编码不能为空";
            return errorMessage;
        }
        if (ObjectUtil.isEmpty(fastCaseRegisterSaveDto.getHandlePersonInfoList())) {
            errorMessage = "办案人员不能为空";
            return errorMessage;
        }
        if (ObjectUtil.isEmpty(fastCaseRegisterSaveDto.getPartyType())) {
            errorMessage = "当事人类型不能为空";
            return errorMessage;
        }
        if (ObjectUtil.isEmpty(fastCaseRegisterSaveDto.getCaseReasonInfoList())) {
            errorMessage = "案由不能为空";
            return errorMessage;
        }
        BeanUtils.copyProperties(fastCaseRegisterSaveDto, saveDto);
        String partyType = fastCaseRegisterSaveDto.getPartyType();
        List<CaseRegisterPartiesPersonInfoDto> fastPartiesPersonInfoList = new ArrayList<>();
        List<CaseRegisterPartiesLegalInfoDto> fastPartiesLegalInfoList = new ArrayList<>();
        //当事人处理
        if (PartyTypeEnum.PERSON.getCode().equals(fastCaseRegisterSaveDto.getPartyType())) {
            fastPartiesPersonInfoList.add(fastCaseRegisterSaveDto.getPartiesPersonInfo());
        } else if (PartyTypeEnum.LEGAL.getCode().equals(fastCaseRegisterSaveDto.getPartyType())) {
            fastPartiesLegalInfoList.add(fastCaseRegisterSaveDto.getPartiesLegalInfo());
        }
        saveDto.setPartiesPersonInfoList(fastPartiesPersonInfoList);
        saveDto.setPartiesLegalInfoList(fastPartiesLegalInfoList);

        if (!PartyTypeEnum.isLegalEnumCode(partyType)) {
            errorMessage = "当事人类型错误";
            return errorMessage;
        }
        //法人当事人数量
        int partiesLegalCount = ObjectUtil.isEmpty(saveDto.getPartiesLegalInfoList()) ? 0 : saveDto.getPartiesLegalInfoList().size();
        //个人当事人数量
        int partiesPersonCount = ObjectUtil.isEmpty(saveDto.getPartiesPersonInfoList()) ? 0 : saveDto.getPartiesPersonInfoList().size();
        if (PartyTypeEnum.PERSON.getCode().equals(partyType) && partiesPersonCount == 0) {
            errorMessage = "当事人为个人时, 个人信息不能为空";
            return errorMessage;
        } else if (PartyTypeEnum.LEGAL.getCode().equals(partyType) && partiesLegalCount == 0) {
            errorMessage = "当事人为法人时, 法人信息不能为空";
            return errorMessage;
        }

        //当事人总数
        int partiesCount = partiesLegalCount + partiesPersonCount;
        //2、校验当事人信息
        if (partiesLegalCount > 1) {
            errorMessage = "企业当事人只能有一个";
            return errorMessage;
        }
        if (partiesCount < 1) {
            errorMessage = "必须选择至少一个当事人";
            return errorMessage;
        } else if (partiesCount > 1) {
            errorMessage = "只能有一个当事人";
            return errorMessage;
        }
        //处罚事项校验
        if (ObjectUtil.isEmpty(saveDto.getCaseReasonInfoList())) {
            errorMessage = "必须选择一个处罚事项";
            return errorMessage;
        }
        int caseReasonCount = saveDto.getCaseReasonInfoList().size();
        if (caseReasonCount > 1) {
            errorMessage = "只能选择一个处罚事项";
            return errorMessage;
        }

        List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoForPdfList = new ArrayList<>();

        //4、校验法人当事人信息的合法性
        List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoDtos = saveDto.getPartiesLegalInfoList();
        if (partiesLegalCount > 0) {
            List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoForPdfList = new ArrayList<>();
            for (CaseRegisterPartiesLegalInfoDto legalInfoDto : partiesLegalInfoDtos) {
                CustomCheckParamUtil.doCheck(legalInfoDto);
                if (!SocialCreditCodeUtil.isValidEntCode(legalInfoDto.getUniscid(), legalInfoDto.getEntType())) {
                    return "统一社会信用代码：" + legalInfoDto.getUniscid() + "不符合规范";
                }
                CaseRegisterPartiesLegalInfoDto partiesLegalInfoDto = new CaseRegisterPartiesLegalInfoDto();
                BeanUtils.copyProperties(legalInfoDto, partiesLegalInfoDto);
                partiesLegalInfoDto.setPhone(ObjectUtils.isEmpty(legalInfoDto.getPhone()) ? "/" : legalInfoDto.getPhone());
                partiesLegalInfoDto.setJob(ObjectUtils.isEmpty(legalInfoDto.getJob()) ? "/" : legalInfoDto.getJob());
                partiesLegalInfoDto.setLegalCertNo(ObjectUtils.isEmpty(legalInfoDto.getLegalCertNo()) ? "/" : legalInfoDto.getLegalCertNo());
                partiesLegalInfoDto.setPostCode(BaseUtil.transferNullToSlash(partiesLegalInfoDto.getPostCode()));
                // 应急条线参数设置
                // 当事人基本情况：统一社会信用代码：【统一社会信用代码值】，法定发表人或负责人：【法定发表人或负责人值】
                // 例：统一社会信用：1321231321，法定代表人：张三
                String partyBasicInfo = "统一社会信用：" + legalInfoDto.getUniscid() + "，法定代表人：" + legalInfoDto.getLegal();
                legalInfoDto.setPartyBasicInfo(partyBasicInfo);
                partiesLegalInfoDto.setPartyBasicInfo(partyBasicInfo);
                partiesLegalInfoForPdfList.add(partiesLegalInfoDto);

            }
            saveDto.setLegalInfoDto(partiesLegalInfoDtos.get(0));
            saveDto.setPartiesLegalInfoForPdfList(partiesLegalInfoForPdfList);

        }

        //5、校验个人当事人信息的合法性
        List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoList = saveDto.getPartiesPersonInfoList();
        if (partiesPersonCount > 0) {
            //判断是否有重复用户
            Map<Object, Long> personInfoCollect = partiesPersonInfoList.stream().collect(
                    Collectors.groupingBy(CaseRegisterPartiesPersonInfoDto::getCertNo, Collectors.counting()));
            List<Object> repeatCertNos = personInfoCollect.keySet().stream().
                    filter(key -> personInfoCollect.get(key) > 1).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(repeatCertNos) && repeatCertNos.size() > 0) {
                String collect = repeatCertNos.stream().map(e -> e.toString()).collect(Collectors.joining(","));
                errorMessage = "当事人证件号" + collect + "重复";
                return errorMessage;
            }

            for (CaseRegisterPartiesPersonInfoDto personInfoDto : partiesPersonInfoList) {
                CustomCheckParamUtil.doCheck(personInfoDto);
                //校验身份证是否合法
                if (StringUtils.isNotEmpty(personInfoDto.getCertNo()) && personInfoDto.getCertType().equals("SFZ")) {
                    boolean flag = commonService.checkRealNameDifferent(personInfoDto.getCertNo(), personInfoDto.getName());
                    if (flag) {
                        errorMessage = "当事人" + personInfoDto.getName() + "证件号码和姓名不匹配";
                        return errorMessage;
                    }
                }
                String certType = CertTypeEnum.getValueByCode(personInfoDto.getCertType());
                personInfoDto.setCertTypeAndCertNo(certType + " " + personInfoDto.getCertNo());
                personInfoDto.setCertTypeName(certType);
                personInfoDto.setBirthStr(BaseUtil.getFormatDate(personInfoDto.getBirth()));
                CaseRegisterPartiesPersonInfoDto partiesPersonInfoForPdf = new CaseRegisterPartiesPersonInfoDto();
                BeanUtils.copyProperties(personInfoDto, partiesPersonInfoForPdf);
                partiesPersonInfoForPdf.setMobile(ObjectUtils.isEmpty(personInfoDto.getMobile()) ? "/" : personInfoDto.getMobile());
                partiesPersonInfoForPdf.setUnitName(ObjectUtils.isEmpty(personInfoDto.getUnitName()) ? "/" : personInfoDto.getUnitName());
                partiesPersonInfoForPdf.setPostCode(BaseUtil.transferNullToSlash(personInfoDto.getPostCode()));
                // 应急条线参数设置
                // 当事人基本情况：性别：【性别值】，出生日期：【出生日期值】，【身份证件类型】号码：【身份证件号码】
                // 例：性别：男，出生日期：2022年9月5日，公民身份证号码：1231231，住址：天津市河西区423123123
                String partyBasicInfo = "性别：" + personInfoDto.getSex() + "，出生日期：" + personInfoDto.getBirthStr() +
                        "，公民身份证号码：" + personInfoDto.getCertNo() + "，住址：" + personInfoDto.getAddress();
                personInfoDto.setPartyBasicInfo(partyBasicInfo);
                partiesPersonInfoForPdf.setPartyBasicInfo(partyBasicInfo);
                partiesPersonInfoForPdf.setCompanyName("/");
                partiesPersonInfoForPdf.setUniscid("/");
                if (ObjectUtils.isEmpty(personInfoDto.getUnitName())) {
                    partiesPersonInfoForPdf.setUnitNameAndJob("/");
                } else {
                    partiesPersonInfoForPdf.setUnitNameAndJob(personInfoDto.getUnitName());
                }

                partiesPersonInfoForPdfList.add(partiesPersonInfoForPdf);
            }
        }
        saveDto.setPartiesPersonInfoForPdfList(partiesPersonInfoForPdfList);
        // 处理添加：案件案由、当事人类型 ; 处罚方式
        saveDto.setPartiesCount(partiesCount);
        saveDto.setCaseReasonCount(saveDto.getCaseReasonCount());
        String casePartiesReasonType = PartiesReasonTypeEnum.SINGLE_PARTY.getCode();
        String handleType = HandleTypeEnum.NORMAL_PUNISH.getCode();
        if (!ObjectUtils.isEmpty(saveDto.getCaseHappenTime())) {
            saveDto.setCaseHappenTimeStr(DateTimeFormatter.ofPattern("yyyy年M月d日").format(BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime())));
        }
        saveDto.setHandleType(handleType);
        saveDto.setCasePartiesReasonType(casePartiesReasonType);
        return errorMessage;
    }

    /**
     * 描述：处理简案快办案件登记，办案人员信息
     *
     * @author zhengqiang
     * @date 2023/08/23
     */
    private void dealFastCaseRegisterHandlePersonInfo(List<CaseHandlePersonInfoDto> caseHandlePersonInfoDtoList, String caseId, UserDTO userInfo) {
        // 校验办案人员信息
        List<CaseHandlePersonInfoDto> mainHandlePersonList = caseHandlePersonInfoDtoList.stream().filter(e -> Constant.STRING_1.equals(e.getHandlePersonType())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(mainHandlePersonList) || mainHandlePersonList.size() < 1) {
            throw new BusinessException("主办人员不能为空");
        } else if (mainHandlePersonList.size() > 1) {
            throw new BusinessException("主办人员不能大于一个");
        }
        //删除之前的办案人员
        Example example = new Example(CaseHandlePersonRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        caseHandlePersonRecordMapper.deleteByExample(example);
        for (CaseHandlePersonInfoDto handlePersonInfoDto : caseHandlePersonInfoDtoList) {
            CaseHandlePersonRecord caseHandlePersonRecord = new CaseHandlePersonRecord();
            BeanUtils.copyProperties(handlePersonInfoDto, caseHandlePersonRecord);
            caseHandlePersonRecord.setHandlePersonType(handlePersonInfoDto.getHandlePersonType());
            caseHandlePersonRecord.setDingId(handlePersonInfoDto.getDingId());
            if (ObjectUtil.isNotEmpty(handlePersonInfoDto.getHandlePersonId())) {
                String lawEnforcementCert = xzzfInterfaceService.getLawEnforcementCertWithUserId(handlePersonInfoDto.getHandlePersonId());
                if (ObjectUtil.isEmpty(lawEnforcementCert)) {
                    throw new BusinessException("办案人员" + handlePersonInfoDto.getHandlePersonName() + "的执法证为空!");
                }
                caseHandlePersonRecord.setLawEnforcementCert(lawEnforcementCert);
                handlePersonInfoDto.setLawEnforcementCert(lawEnforcementCert);
            }
            //  签名校验
            String handlePersonSignPic = null;
            try {
                handlePersonSignPic = commonService.getHandleSignData(handlePersonInfoDto.getHandlePersonId());
            } catch (Exception e) {
                e.printStackTrace();
                if ("true".equals(isCheckHandleSign)) {
                    if (ObjectUtil.isEmpty(handlePersonSignPic)) {
                        throw new BusinessException("因未获取承办人员" + handlePersonInfoDto.getHandlePersonName() + "有效签名信息，无法提交");
                    }
                }
            }
            caseHandlePersonRecord.setHandleSignPic(handlePersonSignPic);
            caseHandlePersonRecord.setId(BaseUtil.createUid());
            caseHandlePersonRecord.setCaseId(caseId);
            caseHandlePersonRecord.setHandleOrgCode(userInfo.getOrgCode());
            caseHandlePersonRecord.setHandleOrgName(userInfo.getOrgName());
            caseHandlePersonRecord.setHandleOrgTel(userInfo.getTelPhone());
            caseHandlePersonRecord.setHandleDeptCode(userInfo.getDeptCode());
            caseHandlePersonRecord.setHandleDeptName(userInfo.getDeptName());
            caseHandlePersonRecord.setHandleDeptTel(userInfo.getTelPhone());
            caseHandlePersonRecord.setHandlePersonTel(handlePersonInfoDto.getHandlePersonTel());
            caseHandlePersonRecord.setStatus(Constant.STRING_1);
            caseHandlePersonRecord.setAddTime(new Date());
            caseHandlePersonRecordMapper.insertSelective(caseHandlePersonRecord);
        }

    }

    public void dealFastCaseRegisterPartiesInfo(CaseRegisterSaveDto saveDto) {
        String caseId = saveDto.getCaseId();
        //删除之前的当事人信息
        CasePartiesRecordSingleQueryDto queryDto = new CasePartiesRecordSingleQueryDto();
        queryDto.setCaseId(caseId);
        List<String> partyIds = new ArrayList<>();
        boolean flag = casePartiesRecordService.delCasePartiesRecordByCaseId(saveDto.getCaseId());
        LocalDateTime createTime = LocalDateTime.now();
        if (flag) {
            List<CaseRegisterPartiesLegalInfoDto> partiesLegalInfoList = new ArrayList<>();
            // 法人当事人
            for (CaseRegisterPartiesLegalInfoDto legalInfoDto : saveDto.getPartiesLegalInfoList()) {
                String partyIdUuid = BaseUtil.createUid();
                legalInfoDto.setId(partyIdUuid);
                CasePartiesLegalInfoDto casePartiesLegalInfo = new CasePartiesLegalInfoDto();
                BeanUtils.copyProperties(legalInfoDto, casePartiesLegalInfo);
                casePartiesLegalInfo.setAddress(legalInfoDto.getUnitAddress());
                casePartiesLegalInfo.setLegalName(legalInfoDto.getLegal());
                casePartiesLegalInfo.setCaseId(caseId);
                casePartiesLegalInfo.setLegalIndustryType(legalInfoDto.getLegalIndustryType());
                casePartiesLegalInfo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
                CasePartiesLegalInfo legalInfo = new CasePartiesLegalInfo();
                BeanUtils.copyProperties(casePartiesLegalInfo, legalInfo);
                if (ObjectUtils.isEmpty(legalInfo.getId())) {
                    legalInfo.setId(BaseUtil.createUid());
                }
                casePartiesLegalInfoMapper.insertSelective(legalInfo);

                //添加当事人表
                CasePartiesRecordDto casePartiesRecordDto = new CasePartiesRecordDto();
                casePartiesRecordDto.setCaseId(saveDto.getCaseId());
                casePartiesRecordDto.setId(BaseUtil.createUid());
                casePartiesRecordDto.setPartyId(partyIdUuid);
                casePartiesRecordDto.setPartyIdentityCode(legalInfoDto.getUniscid());
                casePartiesRecordDto.setPartyIdentityType(null);
                casePartiesRecordDto.setPartyName(legalInfoDto.getEntName());
                casePartiesRecordDto.setPartyType(PartyTypeEnum.LEGAL.getCode());
                createTime = createTime.plusSeconds(1L);
                casePartiesRecordDto.setCreateTime(createTime);
                CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
                BeanUtils.copyProperties(casePartiesRecordDto, casePartiesRecord);
                casePartiesRecordMapper.insertSelective(casePartiesRecord);

                CasePartiesRecord partiesRecord = new CasePartiesRecord();
                BeanUtils.copyProperties(casePartiesRecordDto, partiesRecord);
                partyIds.add(partyIdUuid);
                //处理partyId
                legalInfoDto.setPartyId(partyIdUuid);
                partiesLegalInfoList.add(legalInfoDto);
            }
            List<CaseRegisterPartiesPersonInfoDto> partiesPersonInfoDtoList = new ArrayList<>();
            for (CaseRegisterPartiesPersonInfoDto personInfoDto : saveDto.getPartiesPersonInfoList()) {
                String partyIdUuid = BaseUtil.createUid();
                personInfoDto.setId(partyIdUuid);

                CasePartiesPersonInfoDto casePartiesPersonInfo = new CasePartiesPersonInfoDto();
                BeanUtils.copyProperties(personInfoDto, casePartiesPersonInfo);
                casePartiesPersonInfo.setCaseId(caseId);
                casePartiesPersonInfo.setOperateType(RecordSaveTypeEnum.ADD.getCode());
                String[] addressAreas = personInfoDto.getAddressAreas();
                if (ArrayUtil.isNotEmpty(addressAreas)) {
                    casePartiesPersonInfo.setAddressAreasStr(String.join(",", addressAreas));
                }
                CasePartiesPersonInfo personInfo = new CasePartiesPersonInfo();
                BeanUtils.copyProperties(casePartiesPersonInfo, personInfo);
                if (ObjectUtil.isNotEmpty(casePartiesPersonInfo.getBirth())) {
                    personInfo.setBirth(BaseUtil.getFormatDate(casePartiesPersonInfo.getBirth()));
                }
                //增加年龄处理
                personInfo.setAge(BaseUtil.getAgeByBirth(casePartiesPersonInfo.getBirth()));
                if (ObjectUtils.isEmpty(personInfo.getId())) {
                    personInfo.setId(BaseUtil.createUid());
                }
                casePartiesPersonInfoMapper.insertSelective(personInfo);
                //添加当事人表
                CasePartiesRecordDto casePartiesRecordDto = new CasePartiesRecordDto();
                casePartiesRecordDto.setCaseId(saveDto.getCaseId());
                casePartiesRecordDto.setId(BaseUtil.createUid());
                casePartiesRecordDto.setPartyId(partyIdUuid);
                casePartiesRecordDto.setPartyIdentityCode(personInfoDto.getCertNo());
                casePartiesRecordDto.setPartyIdentityType(personInfoDto.getCertType());
                casePartiesRecordDto.setPartyName(personInfoDto.getName());
                casePartiesRecordDto.setPartyType(PartyTypeEnum.PERSON.getCode());
                createTime = createTime.plusSeconds(1L);
                casePartiesRecordDto.setCreateTime(createTime);
                casePartiesRecordDto.setAddressDetail(personInfoDto.getAddressDetail());
                if (ObjectUtil.isNotEmpty(personInfoDto.getAddressAreas())) {
                    casePartiesRecordDto.setAddressAreas(String.join(",", personInfoDto.getAddressAreas()));
                }
                CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
                BeanUtils.copyProperties(casePartiesRecordDto, casePartiesRecord);
                casePartiesRecordMapper.insertSelective(casePartiesRecord);
                CasePartiesRecord partiesRecord = new CasePartiesRecord();
                BeanUtils.copyProperties(casePartiesRecordDto, partiesRecord);
                partyIds.add(partyIdUuid);
                //处理partyId
                personInfoDto.setPartyId(partyIdUuid);
                partiesPersonInfoDtoList.add(personInfoDto);
            }
            saveDto.setPartyIds(partyIds.stream().collect(Collectors.joining(",")));
            saveDto.setPartiesLegalInfoList(partiesLegalInfoList);
            saveDto.setPartiesPersonInfoList(partiesPersonInfoDtoList);
        }
    }

}
